﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Linq;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using System.Windows.Media.Effects;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using Bling.Core;
using Bling.DSL;
using Bling.WPF;
using Bling.Util;
using Bling.Angles;
using Bling.Reactive;
using Bling.Properties;

namespace Bling.WPF {
  using Bling.Matrices;

  public partial class BrushBl<T, BRAND> : ObjectBl<T, BRAND>, IExtends<BRAND,BrushBl>, IDependencyObjectBl<T, BRAND>
    where T : Brush
    where BRAND : BrushBl<T, BRAND> {
    /// <summary>
    /// Gets or sets the degree of opacity.
    /// </summary>
    public DoubleBl Opacity {
      get { return Provider.Property<T,double>(Brush.OpacityProperty).Bl(); }
      set { Opacity.Bind = value; }
    }
    public Bling.WPF.TransformBl Transform {
      get {
        return new Bling.WPF.TransformBl(Provider.Property<T,Transform>(Brush.TransformProperty)) {};
      }
      set { Transform.Bind = value; }
    }
    public Bling.WPF.TransformBl RelativeTransform {
      get {
        return new Bling.WPF.TransformBl(Provider.Property<T,Transform>(Brush.RelativeTransformProperty)) {
          Origin = new Double2Bl(.5, .5),
        };
      }
      set { RelativeTransform.Bind = value; }
    }
  }
  public partial class BrushBl {
    public static implicit operator BrushBl(ImageSource image) {
      return new Bling.WPF.ImageBrushBl() { ImageSource = image };
    }
    public static implicit operator BrushBl(GeometryBl geometry) {
      return new DrawingBrushBl() { Drawing = new GeometryDrawingBl() { Geometry = geometry } };
    }
    public static implicit operator BrushBl(DrawingBl drawing) {
      return new DrawingBrushBl() { Drawing = drawing };
    }
    public static implicit operator BrushBl(ColorBl color) {
      Expr<Color> clr = color;
      return clr.Map<Brush>(clr0 => {
        return new SolidColorBrush() { Color = clr0 };
      });
      //return new Bling.WPF.SolidColorBrushBl() { Color = color };
    }
    public static implicit operator BrushBl(Color color) {
      return ((ColorBl)color);
    }
    public static explicit operator SolidColorBrushBl(BrushBl from) {
      return from.DownCast<SolidColorBrushBl>();
    }
    public static explicit operator ImageBrushBl(BrushBl from) {
      return from.DownCast<ImageBrushBl>();
    }
  }


  /// <summary>
  /// Anything that undergoes rendering.
  /// </summary>
  public abstract class RenderBl<T, BRAND> : Brand<T, BRAND>, ICoreBrandT, IDependencyObjectBl<T,BRAND>
    where T : DependencyObject
    where BRAND : RenderBl<T, BRAND> {
    public RenderBl(Expr<T> Underlying) : base(Underlying) { }
    public RenderBl() : base() { }
    /// <summary>
    /// Either Unspecified or Aliased.  If unspecified, no edge mode is specified. Do not alter the current edge mode of non-text
    ///     drawing primitives. This is the default value.
    /// If Aliased, render the edges of non-text drawing primitives as aliased edges.
    /// </summary>
    public EnumBl<EdgeMode> EdgeMode {
      get { return Provider.Property<T,EdgeMode>(RenderOptions.EdgeModeProperty); }
      set { EdgeMode.Bind = value; }
    }
    /// <summary>
    /// When animating the scale of any bitmap, the default high-quality image re-sampling algorithm 
    /// can sometimes consume sufficient system resources to cause frame rate degradation, effectively 
    /// causing animations to stutter. By setting the BitmapScalingMode property of the RenderOptions 
    /// object to LowQuality you can create a smoother animation when scaling a bitmap. LowQuality 
    /// mode tells the WPF rendering engine to switch from a quality-optimized algorithm to a speed-optimized 
    /// algorithm when processing images.
    /// </summary>
    public EnumBl<BitmapScalingMode> BitmapScalingMode {
      get { return Provider.Property<T,BitmapScalingMode>(RenderOptions.BitmapScalingModeProperty); }
      set { BitmapScalingMode.Bind = value; }
    }
    /// <summary>
    /// The idea is you set CacheHint to Cache to tell us to try to avoid updating the brush. 
    /// Now if you scaled the brush way up, it could look terrible and if you scale it down 
    /// it could look bad as well. So min/max thresholds are relative scales to the initial 
    /// size of the brush that tell us when to update things again. For example, if you set 
    /// ThresholdMinimum to .5 and the brush size halves, we’ll update the brush and cache the new result.
    /// </summary>
    public EnumBl<CachingHint> CachingHint {
      get { return Provider.Property<T,CachingHint>(RenderOptions.CachingHintProperty); }
      set { CachingHint.Bind = value; }
    }
    private class CacheInvalidationThresholdSet : RangeBl<DoubleBl,DoubleBl> {
      internal Expr<T> Underlying;
      public override DoubleBl Minimum {
        get { return Underlying.Property<T,double>(RenderOptions.CacheInvalidationThresholdMinimumProperty); }
        set { Minimum.Bind = value; }
      }
      public override DoubleBl Maximum {
        get { return Underlying.Property<T,double>(RenderOptions.CacheInvalidationThresholdMaximumProperty); }
        set { Maximum.Bind = value; }
      }
    }
    /// <summary>
    /// WPF has introduced the cache scheme for those pre-rasterized content, 
    /// you could twist the cache hint through RenderOptions.CacheInvalidationThresholdMaximum 
    /// and  RenderOptions.CacheInvalidationThresholdMinimum attached properties, those two 
    /// properties could help to determine in what extent the rasterized bitmap will be scaled up 
    /// and down, it the scaling factor exceeds the threshold specified by 
    /// RenderOptions.CacheInvalidationThresholdMaximum and  RenderOptions.CacheInvalidationThresholdMinimum 
    /// attached properties, WPF will regenerate those bitmap by kicking off the software rendering pipeline again.
    /// </summary>
    public RangeBl<DoubleBl,DoubleBl> CacheInvalidationThreshold {
      get { return new CacheInvalidationThresholdSet() { Underlying = Provider }; }
      set { CacheInvalidationThreshold.Bind(value); }
    }
  }
  /// <summary>
  ///     Provides rendering support in WPF, which includes hit testing, coordinate
  ///     transformation, and bounding box calculations.
  /// </summary>
  public abstract class VisualBl<T, BRAND> : RenderBl<T, BRAND>, IExtends<BRAND,VisualBl>
    where T : Visual
    where BRAND : VisualBl<T, BRAND> {
    public VisualBl(Expr<T> Underlying) : base(Underlying) { }
    public VisualBl() : base() { }
    public static implicit operator VisualBl(VisualBl<T, BRAND> mat) {
      return VisualBl.UpCast(mat);
    }
  }
  /// <summary>
  ///     Provides rendering support in WPF, which includes hit testing, coordinate
  ///     transformation, and bounding box calculations.
  /// </summary>
  public class VisualBl : VisualBl<Visual, VisualBl> {
    public VisualBl() : base() { }
    public VisualBl(Expr<Visual> Underlying) : base(Underlying) { }
    public static implicit operator VisualBl(Expr<Visual> target) { return new VisualBl((target)); }
    public static implicit operator VisualBl(Visual target) { return (new Constant<Visual>(target)); }
  }

  public abstract class UIElementBl<T, BRAND> : VisualBl<T, BRAND>, IExtends<BRAND,UIElementBl>
    where T : UIElement
    where BRAND : UIElementBl<T, BRAND> {
    public UIElementBl(Expr<T> Underlying) : base(Underlying) { }
    public UIElementBl() : base() { }
    public static implicit operator UIElementBl(UIElementBl<T, BRAND> mat) {
      return UIElementBl.UpCast(mat);
    }

    private static GetProperty<T, int> WriteMouseCapturedProperty;
    private static GetProperty<T, bool> HasKeyboardFocusProperty;

    //private static GetProperty<T,List<ExplicitClient>> MousePositionListenersProperty;
    //private Func<List<ExplicitClient>> MousePositionListenersF;
    
    private static GetProperty<T, TimeSpan> HoldTimeProperty = null;
    private static GetProperty<T, MouseSet.TapAdapter> TapAdapterProperty;
    private Func<MouseSet.TapAdapter> TapAdapterF;
    //private Func<TimeSpan> HoldTimeF;
    
    [System.ThreadStatic]
    private static int? MouseWheelDelta0;

    /// <summary>
    /// Organizes mouse functionality and acts as a state for mouse down/up.
    /// </summary>
    public class MouseSet : State {
      internal BRAND Outer;

      public class CaptureSet {
        internal BRAND Outer;
        /// <summary>
        /// Gets a value indicating whether the mouse is captured to this element. When set to true, the mouse is captured on this UI element.
        /// </summary>
        /// <returns>
        ///     true if the element has mouse capture; otherwise, false. The default is false.
        ///</returns>
        public BoolBl Has {
          get {
            return Outer.Provider.Property<T,bool>(UIElement.IsMouseCapturedProperty);
          }
        }
        /// <summary>
        ///     Gets a value that determines whether mouse capture is held by this element
        ///     or by child elements in its visual tree. This is a dependency property. Returns
        ///     true if this element or a contained element has mouse capture; otherwise,
        ///     false.
        /// </summary>
        public BoolBl HasWithin {
          get {
            return Outer.Provider.Property<T,bool>(UIElement.IsMouseCaptureWithinProperty);
          }
        }

        /// <summary>
        /// How many times this UI element has captured the mouse. This is a dependency property
        /// that will automatically cause the mouse to be captured on this UI element when it goes from zero to non-zero, and
        /// will automatically cause the mouse to be uncaptured when it goes from non-zero to zero.
        /// </summary>
        public IntBl Count {
          get {
            if (WriteMouseCapturedProperty == null) {
              WriteMouseCapturedProperty = "WriteMouseCaptured".NewProperty<T, int>(0, (value, oldV, newV) => {
                if (newV > 0 && oldV == 0) {
                  System.Windows.Input.Mouse.Capture(value, CaptureMode.Element);
                } else if (newV == 0 && oldV > 0) {
                  System.Windows.Input.Mouse.Capture(value, CaptureMode.None);
                }
              });

            }
            return WriteMouseCapturedProperty[Outer];
          }
          set {
            Count.Bind = value;
          }
        }
        /// <summary>
        /// Can the mouse be safely captured for this UI element? 
        /// This is not a dependency property and so does not support change propagation.
        /// Returns true if the mouse is not currently captured or this UI element has already captured it.
        /// </summary>
        public BoolBl Can {
          get {
            return Outer.StatefulMap<bool, BoolBl>(ui => {
              return System.Windows.Input.Mouse.Captured == null ||
                     System.Windows.Input.Mouse.Captured == ui;
            });
          }
        }
        /// <summary>
        ///     Occurs when this element captures the mouse.
        /// </summary>
        public EventStream Got {
          get {
            // until later.
            Outer.IsConstant.Assert();
            var CurrentValue = Outer.CurrentValue;
            return new DefaultEventStream<MouseEventHandler>() {
              Transform = a => (x, y) => a(),
              Add = a => CurrentValue.GotMouseCapture += a,
              Remove = a => CurrentValue.GotMouseCapture -= a,
            };
          }
        }
        /// <summary>
        ///     Occurs when this element loses mouse capture.
        /// </summary>
        public EventStream Lost {
          get {
            // until later.
            Outer.IsConstant.Assert();
            var CurrentValue = Outer.CurrentValue;
            return new DefaultEventStream<MouseEventHandler>() {
              Transform = a => (x, y) => a(),
              Add = a => CurrentValue.LostMouseCapture += a,
              Remove = a => CurrentValue.LostMouseCapture -= a,
            };
          }
        }
      }
      public CaptureSet Capture { get { return new CaptureSet() { Outer = Outer }; } }

      /// <summary>
      /// Get the current mouse position with respect to this UI element. This is a read-only property is automatically updated when data bound.
      /// </summary>
      public Double2Bl Position {
        get {
          var CurrentValueF = Outer.AsFunc;

          var Changed0 = Outer.Map<Window,WindowBl>(v =>  Window.GetWindow(v)).Mouse.Move;

          var e = new ExplicitPropertyExpr<Point>((e0) => {
            MouseEventHandler handler = null;
            Action<Window> F = window => {
              handler = (x, y) => {
                if (!e0.DoUpdate())
                  window.MouseMove -= handler;
              };
              window.MouseMove += handler;
            };
            var window0 = Window.GetWindow(CurrentValueF());
            if (window0 != null) F(window0);
            else if (CurrentValueF() is FrameworkElement) {
              var fe = ((FrameworkElement)(object)CurrentValueF());
              (!fe.IsLoaded).Assert();
              fe.Loaded += (x, y) => {
                var window1 = Window.GetWindow((FrameworkElement)x);
                (window1 != null).Assert();
                F(window1);
              };
            } else throw new NotSupportedException();
          }, () => System.Windows.Input.Mouse.GetPosition(CurrentValueF()), Changed0); 
          return e.Bl();
        }
      }
      /// <summary>
      /// Specify mouse hold timeout. The default is TimeSpan.Zero, which means that the hold state of the mouse is disabled causing the mouse to remain in ready mode. 
      /// </summary>
      public TimeSpanBl HoldTimeout {
        get {
          if (HoldTimeProperty == null)
            HoldTimeProperty = "HoldTime".NewProperty<T, TimeSpan>(TimeSpan.Zero);
          return HoldTimeProperty[Outer];
        }
        set { HoldTimeout.Bind = value; }
      }
      internal class TapAdapter : Machine {
        public readonly Machine.LocalState Ready;
        public readonly Machine.LocalState Hold;
        public readonly Machine.LocalState Drag;
        public readonly Machine.LocalState Click;
        public TapAdapter(BRAND ui) {
          Name = "TapAdapter";
          Ready = this.MakeState("Ready");
          Hold = this.MakeState("Hold");
          Drag = this.MakeState("Drag");
          Click = this.MakeState("Click");

          Initial[ui.Mouse.Down & ui.Mouse.Capture.Can] = Ready;
          Ready[ui.Mouse.HoldTimeout.AlarmUI()] = Hold;
          Hold[ui.Mouse.Up] = Initial;
          Hold[ui.Mouse.Move] = Hold;

          Ready[ui.Mouse.Move] = Drag;
          Drag[ui.Mouse.Move] = Drag;
          Drag[ui.Mouse.Up] = Initial;

          Ready[ui.Mouse.Up] = Click;
          Click.Epsilon = Initial;
          Activate();
        }
        public State InUse { get { return !Initial; } }
      }

      private TapAdapter TapAdapterContext {
        get {
          if (TapAdapterProperty == null) {
            /*
            TapAdapter.Instance.DoHold = (ui) => {
              if (HoldTimeProperty == null) return EventStream.Null;
              if (ui.HoldTimeF == null) ui.HoldTimeF = ui.Mouse.HoldTimeout.AsFunc;

              return ui.HoldTimeF().AlarmUI();
            };*/
            TapAdapterProperty =
              "TapAdapter".NewProperty<T, TapAdapter>();
          }
          if (Outer.TapAdapterF == null) Outer.TapAdapterF = TapAdapterProperty[Outer].AsFunc;
          if (Outer.TapAdapterF() == null) {
            var adapter = new TapAdapter(Outer);
            Outer.CurrentValue.SetValue(TapAdapterProperty.Property, adapter);
            Capture.Count[adapter.InUse.In] = Capture.Count + 1;
            Capture.Count[adapter.InUse.Out] = Capture.Count - 1;
            Outer.CurrentValue.SetValue(TapAdapterProperty.Property, adapter);
          }
          return Outer.TapAdapterF();
        }
      }
      /// <summary>
      /// The mouse is in this state if it is mouse pressed and another element is not in the InUse state. While in the InUse state,
      /// mouse events are captured by this element.
      /// </summary>
      public State InUse { get { return TapAdapterContext.InUse; } }
      /// <summary>
      /// This state is entered from the ready (mouse pressed) state after a certain amount of time (HoldTimeout).
      /// </summary>
      public State Hold { get { return TapAdapterContext.Hold; } }
      /// <summary>
      /// This state is entered from the ready (mouse pressed) state when the mouse has been moved.
      /// </summary>
      public State Drag { get { return TapAdapterContext.Drag; } }
      /// <summary>
      /// An event is fired on this stream when from the ready (mouse pressed) state the mouse is released.
      /// </summary>
      public EventStream Click { get { return TapAdapterContext.Click.In; } }
      /// <summary>
      /// Organize mouse wheel functionality.
      /// </summary>
      public class WheelSet : DefaultEventStream<MouseWheelEventHandler> {
        internal readonly BRAND Outer;
        internal WheelSet(BRAND Outer) {
          this.Outer = Outer;
          Outer.IsConstant.Assert();
          var CurrentValue = Outer.CurrentValue;
          Transform = a => (x, y) => {
            (MouseWheelDelta0 == null).Assert();
            MouseWheelDelta0 = y.Delta;
            a();
            (MouseWheelDelta0 != null).Assert();
            MouseWheelDelta0 = null;
          };
          Add = a => CurrentValue.MouseWheel += a;
          Remove = a => CurrentValue.MouseWheel -= a;

        }
        /// <summary>
        ///     Gets a value that indicates the amount that the mouse wheel has changed.
        ///
        /// Returns the amount the wheel has changed. This value is positive if the mouse wheel
        ///     is rotated in an upward direction (away from the user) or negative if the
        ///     mouse wheel is rotated in a downward direction (toward the user).
        /// </summary>
        /// <exception cref="InvalidOperationException">If the wheel delta is looked at outside of an At event context.</exception>
        public IntBl Delta {
          get {
            return IntBl.State(() => {
              if (MouseWheelDelta0 == null) throw new InvalidOperationException("Cannot look at wheel delta outside of event");
              return (int)MouseWheelDelta0;
            });
          }
        }
      }
      /// <summary>
      /// A stream of this mouse's wheel events. 
      /// </summary>
      public WheelSet Wheel { get { return new WheelSet(Outer); } }

      public override Func<bool> IsCurrentState {
        get {
          var Cf = Outer.AsFunc;
          return () =>
            System.Windows.Input.Mouse.LeftButton == MouseButtonState.Pressed &&
            (System.Windows.Input.Mouse.Captured == Cf() ||
             (System.Windows.Input.Mouse.Captured == null && Cf().IsMouseOver));
        }
      }
      public override string ToString() { return Outer + ".Mouse"; }



      /// <summary>
      ///     Occurs when any mouse button is pressed while the pointer is over this element
      ///     while another UI element has not entered the mouse state. When entering this
      ///     state, the mouse is captured on this UI element until mouse up is detected.
      /// </summary>
      public override EventStream In {
        get {
          (Outer.IsConstant).Assert();
          var Cf = Outer.CurrentValue;
          return new EnterStream() { Outer = this, Cf = Cf, };
        }
      }
      private class EnterStream : EventStream {
        internal MouseSet Outer;
        internal T Cf;
        private Action DoInc, DoDec;
        public override Action Subscribe(Action a) {
          if (DoInc == null) {
            DoInc = IntBl.Assign(Outer.Capture.Count, Outer.Capture.Count + 1);
            DoDec = IntBl.Assign(Outer.Capture.Count, Outer.Capture.Count - 1);
          }
          Action aa = null;
          aa = () => {
            DoInc();
            a();
            Outer.Up.Subscribe(() => {
              DoDec();
            });
          };
          // don't enter this state if the mouse state is entered on another element.
          return (Outer.Down & Outer.Capture.Can).Subscribe(aa);
        }
      }
      /// <summary>
      ///     Occurs when any mouse button is released over this element.
      /// </summary>
      public override EventStream Out { get { return Up; } }
      public override EventStream Update { get { return EventStream.Null; } }

      /// <summary>
      ///     Occurs when the mouse pointer enters the bounds of this element.
      /// </summary>
      public EventStream Enter {
        get {
          // until later.
          Outer.IsConstant.Assert();
          var CurrentValue = Outer.CurrentValue;
          return new DefaultEventStream<MouseEventHandler>() {
            Transform = a => (x, y) => a(),
            Add = a => CurrentValue.MouseEnter += a,
            Remove = a => CurrentValue.MouseEnter -= a,
          };
        }
      }
      /// <summary>
      ///    Gets a value indicating whether the mouse pointer is located over this element
      ///     (including child elements in the visual tree). This is a dependency property. Returns
      ///     true if mouse pointer is over the element or its child elements; otherwise,
      ///     false. The default is false. 
      /// </summary>
      public BoolBl IsOver {
        get { return Outer.Provider.Property<T,bool>(UIElement.IsMouseOverProperty); }
      }
      /// <summary>
      ///     Gets a value that indicates whether the position of the mouse pointer corresponds
      ///     to hit test results, which take element compositing into account. This is
      ///     a dependency property. Returns
      ///     true if the mouse pointer is over the same element result as a hit test;
      ///     otherwise, false. The default is false.
      /// </summary>
      public BoolBl IsDirectlyOver {
        get { return Outer.Provider.Property<T,bool>(UIElement.IsMouseDirectlyOverProperty); }
      }

      /// <summary>
      ///     Occurs when the mouse pointer enters the bounds of this element.
      /// </summary>
      public EventStream Leave {
        get {
          // until later.
          Outer.IsConstant.Assert();
          var CurrentValue = Outer.CurrentValue;
          return new DefaultEventStream<MouseEventHandler>() {
            Transform = a => (x, y) => a(),
            Add = a => CurrentValue.MouseLeave += a,
            Remove = a => CurrentValue.MouseLeave -= a,
          };
        }
      }

      /// <summary>
      ///     Occurs when any mouse button is pressed while the pointer is over this element.
      /// </summary>
      public EventStream Down {
        get {
          // until later.
          Outer.IsConstant.Assert();
          var CurrentValue = Outer.CurrentValue;
          return new DefaultEventStream<MouseButtonEventHandler>() {
            Transform = a => (x, y) => a(),
            Add = a => CurrentValue.MouseDown += a,
            Remove = a => CurrentValue.MouseDown -= a,
          };
        }
      }
      /// <summary>
      ///     Occurs when any mouse button is released over this element.
      /// </summary>
      public EventStream Up {
        get {
          // until later.
          Outer.IsConstant.Assert();
          var CurrentValue = Outer.CurrentValue;
          return new DefaultEventStream<MouseButtonEventHandler>() {
            Transform = a => (x, y) => a(),
            Add = a => CurrentValue.MouseUp += a,
            Remove = a => CurrentValue.MouseUp -= a,
          };
        }
      }
      /// <summary>
      ///     Occurs when the mouse pointer moves while over this element.
      /// </summary>
      public EventStream Move {
        get {
          // until later.
          //Outer.IsConstant.Assert();
          var CurrentValue = Outer.CurrentValue;
          return new DefaultEventStream<MouseEventHandler>() {
            Transform = a => (x, y) => a(),
            Add = a => CurrentValue.MouseMove += a,
            Remove = a => CurrentValue.MouseMove -= a,
          };
        }
      }
    }
    /// <summary>
    /// Organizes mouse functionality and acts as a state for mouse down/up.
    /// </summary>
    public MouseSet Mouse { get { return new MouseSet() { Outer = this }; } }


    [System.ThreadStatic]
    private static Key? KeyInvolved;

    /// <summary>
    /// Organizes keyboard behavior.
    /// </summary>
    public class KeysSet : MultiState<Key,EnumBl<Key>> {
      internal BRAND Outer;
      private static void Activate(Action a, KeyEventArgs e) {
        (KeyInvolved == null).Assert();
        KeyInvolved = e.Key;
        a();
        (KeyInvolved != null).Assert();
        KeyInvolved = null;
      }
      public override EventStream In {
        get { return Down; }
      }
      protected override EventStream Out0 {
        get { return Up; }
      }
      protected override EventStream Update0 {
        get { return EventStream.Null; }
      }
      protected override Key Target0 {
        get {
          if (KeyInvolved == null) throw new InvalidOperationException("not in keyboard event");
          return (Key)KeyInvolved;
        }
      }
      public override Func<bool> IsCurrentState(EnumBl<Key> Value) {
        return Value.StatefulMap<bool, BoolBl>(key => {
          return System.Windows.Input.Keyboard.IsKeyDown(key);
        }).AsFunc;
      }

      public class FocusSet : State {
        public BRAND Outer;
        /// <summary>
        ///     Gets a value indicating whether this element has keyboard focus. This is
        ///     a dependency property. Returns
        ///     true if this element has keyboard focus; otherwise, false. The default is
        ///     false.
        /// </summary>
        public BoolBl Has {
          get {
            return Outer.Provider.Property<T,bool>(UIElement.IsKeyboardFocusedProperty);
          }
        }
        /// <summary>
        ///     Gets a value indicating whether keyboard focus is anywhere within the element
        ///     or its visual tree child elements. This is a dependency property. Returns
        ///     true if keyboard focus is on the element or its child elements; otherwise,
        ///     false.
        /// </summary>
        public BoolBl HasWithin {
          get {
            return Outer.Provider.Property<T,bool>(UIElement.IsKeyboardFocusWithinProperty);
          }
        }
        /// <summary>
        ///     Gets or sets a value that indicates whether the element can receive focus.
        ///     This is a dependency property. Returns true if the element is focusable; otherwise false. The default is false,
        ///     but see Remarks.
        /// </summary>
        public BoolBl Enabled {
          get { return Outer.Provider.Property<T,bool>(UIElement.FocusableProperty); }
          set { Enabled.Bind = value; }
        }
        /// <summary>
        ///     Occurs when the keyboard is focused on this element.
        /// </summary>
        public EventStream Got {
          get {
            Outer.IsConstant.Assert();
            var CurrentValue = Outer.CurrentValue;
            return new DefaultEventStream<KeyboardFocusChangedEventHandler>() {
              Transform = a => (x, y) => a(),
              Add = a => CurrentValue.GotKeyboardFocus += a,
              Remove = a => CurrentValue.GotKeyboardFocus -= a,
            };
          }
        }
        /// <summary>
        ///     Occurs when the keyboard is focused on this element.
        /// </summary>
        public EventStream Lost {
          get {
            Outer.IsConstant.Assert();
            var CurrentValue = Outer.CurrentValue;
            return new DefaultEventStream<KeyboardFocusChangedEventHandler>() {
              Transform = a => (x, y) => a(),
              Add = a => CurrentValue.LostKeyboardFocus += a,
              Remove = a => CurrentValue.LostKeyboardFocus -= a,
            };
          }
        }
        /// <summary>
        /// Try to acquire focus. 
        /// </summary>
        public Command Acquire {
          get {
            return new Command("AcquireFocus", () => {
              var value = Outer.CurrentValue;
              var ret = System.Windows.Input.Keyboard.Focus(value);
              return;
            });
          }
        }

        public override EventStream In { get { return Got; } }
        public override EventStream Out { get { return Lost; } }
        public override EventStream Update { get { return EventStream.Null; } }
        public override Func<bool> IsCurrentState { get { return Has.AsFunc; } }
      }
      /// <summary>
      /// Keyboard focus state, properties, events, and commands for this ui element.
      /// </summary>
      public FocusSet Focus { get { return new FocusSet() { Outer = Outer }; } }


      /// <summary>
      ///     Occurs when a key is pressed while focus is on this element.
      /// </summary>
      public EventStream Down {
        get {
          Outer.IsConstant.Assert();
          var CurrentValue = Outer.CurrentValue;
          return new DefaultEventStream<KeyEventHandler>() {
            Transform = a => (x, y) => {
              if (!y.IsRepeat)
              Activate(a, y);
            },
            Add = a => CurrentValue.KeyDown += a,
            Remove = a => CurrentValue.KeyDown -= a,
          };
        }
      }
      /// <summary>
      ///     Occurs when a key is released while focus is on this element.
      /// </summary>
      public EventStream Up {
        get {
          Outer.IsConstant.Assert();
          var CurrentValue = Outer.CurrentValue;
          return new DefaultEventStream<KeyEventHandler>() {
            Transform = a => (x, y) => Activate(a, y),
            Add = a => CurrentValue.KeyUp += a,
            Remove = a => CurrentValue.KeyUp -= a,
          };
        }
      }
    }
    /// <summary>
    /// Access keyboard behavior and this ui element's keyboard multi-state. 
    /// </summary>
    public KeysSet Keys { get { return new KeysSet() { Outer = this }; } }

    
  }

  public class UIElementBl : UIElementBl<UIElement, UIElementBl> {
    public UIElementBl() : base(new Constant<UIElement>(null)) { }
    public UIElementBl(Expr<UIElement> Underlying) : base(Underlying) { }
    public static implicit operator UIElementBl(Expr<UIElement> target) { return new UIElementBl((target)); }
    public static implicit operator UIElementBl(UIElement target) { return (new Constant<UIElement>(target)); }
    // optional properties

  }

  public abstract partial class TransformBl<T, BRAND> : Brand<T, BRAND>, IExtends<BRAND,TransformBl>
    where T : Transform
    where BRAND : TransformBl<T, BRAND> {
    public TransformBl(Expr<T> v) : base(v) { }
    public TransformBl() : base() { }
    public static implicit operator TransformBl(TransformBl<T, BRAND> self) {
      var ret = TransformBl.UpCast((Brand<BRAND>)self);
      return ret;
    }
    static TransformBl() {
      TransformBl.CheckInit();
    }
  }
  /// <summary>
  ///     Defines functionality that enables transformations in a 2-D plane. Transformations
  ///     include rotation (System.Windows.Media.RotateTransform), scale (System.Windows.Media.ScaleTransform),
  //     skew (System.Windows.Media.SkewTransform), and translation (System.Windows.Media.TranslateTransform).
  ///     This class hierarchy differs from the System.Windows.Media.Matrix structure
  ///     because it is a class and it supports animation and enumeration semantics.
  /// </summary>
  public partial class TransformBl : TransformBl<Transform, TransformBl> {
    public TransformBl(Expr<Transform> v) : base(v) { }
    public TransformBl() : base() { }
    public static implicit operator TransformBl(Expr<Transform> v) { return new TransformBl(v); }
    public static implicit operator TransformBl(Transform t) { return new Constant<Transform>(t); }

    public static void CheckInit() { Extensions.Trace("CheckInit: " + typeof(TransformBl) + " ToBrand=" + ToBrand); }


    /// <summary>
    /// Transforms the specified point according to the transform matrix.
    /// </summary>
    /// <param name="p">Point to be transformed.</param>
    /// <returns>Transformed point.</returns>
    public Double2Bl Transform(Double2Bl p) {
      var p0 = WPFConversions<double, D2, Point>.ToWPF.Instance.Make(p);
      var p2 = Provider.Map2<Point, Point>(p0, (t, p1) => t.Transform(p1));
      return WPFConversions<double, D2, Point>.ToBling.Instance.Make(p);
    }
    /// <summary>
    /// The inverse of this matrix. 
    /// </summary>
    public TransformBl Inverse {
      get { return this.Map(t => (Transform) t.Inverse, t => (Transform) t.Inverse); }
    }
    /// <summary>
    /// Gets or sets the center point of any possible transform declared, relative to the bounds of the element.
    /// </summary>
    public Double2Bl Origin = new Double2Bl(0, 0);

    /// <summary>
    /// Set the center point of the scale/skew/rotate transform .
    /// </summary>
    /// <param name="c">Center point of rotation.</param>
    /// <returns>Itself.</returns>
    public TransformBl this[Double2Bl c] {
      get {
        this.Origin = c;
        return this;
      }
    }
    private TRANSFORM Transform<TRANSFORM>() where TRANSFORM : Transform, new() {
      TRANSFORM transform;
      if (Provider.HasCurrentValue) {
        var current = (Transform)this.CurrentValue;
        if (current is TRANSFORM) transform = (TRANSFORM)current;
        else if (current is TransformGroup) {
          var group = (TransformGroup)current;
          transform = null;
          foreach (var v in group.Children) {
            if (v is TRANSFORM) transform = (TRANSFORM)v;
          }
          if (transform == null) {
            transform = new TRANSFORM();
            group.Children.Add(transform);
          }
        } else if (current == null) {
          transform = new TRANSFORM();
          this.Now = (transform);
        } else {
          var group = new TransformGroup();
          group.Children.Add(current);
          transform = new TRANSFORM();
          group.Children.Add(transform);
          this.Now = (group);
        }
      } else {
        throw new NotSupportedException();
      }
      return transform;
    }
    /// <summary>
    /// Rotate the UI element around center.
    /// </summary>
    public DegreeBl Rotate  {
      get {
        var rotate = Transform<RotateTransform>();
        var px = rotate.Bl<double>(RotateTransform.CenterXProperty).Bl();
        var py = rotate.Bl<double>(RotateTransform.CenterYProperty).Bl();
        (new Double2Bl(px, py)).Bind = Origin;
        var degrees = rotate.Bl<double>(RotateTransform.AngleProperty).Bl();
        return new DegreeBl(degrees);
      }
      set {
        Rotate.Bind = value;
      }
    }
    /// <summary>
    /// Scale the UI element around center.
    /// </summary>
    /// <param name="center">the center point of the scaling</param>
    /// <returns></returns>
    public Double2Bl Scale {
      get {
        var scale = Transform<ScaleTransform>();
        var px = scale.Bl<double>(ScaleTransform.CenterXProperty).Bl();
        var py = scale.Bl<double>(ScaleTransform.CenterYProperty).Bl();
        (new Double2Bl(px, py)).Bind = Origin;

        var sx = scale.Bl<double>(ScaleTransform.ScaleXProperty).Bl();
        var sy = scale.Bl<double>(ScaleTransform.ScaleYProperty).Bl();
        return new Double2Bl(sx, sy);
      }
      set { Scale.Bind = value; }
    }

    /// <summary>
    /// Set scale for both X and Y dimensions around center.
    /// </summary>
    public DoubleBl ScaleXY {
      get {
        var ret = Scale;
        ret.X = ret.Y;
        return ret.Y;
      }
      set {
        ScaleXY.Bind = value;
        //Scale.Bind = new PointBl(value, value);
      }
    }

    /// <summary>
    /// Skew the UI element.
    /// </summary>
    /*
    public DegreePointBl Skew {
      get {
        var skew = Transform<SkewTransform>();
        var px = skew.Bl<double>(SkewTransform.CenterXProperty).Bl();
        var py = skew.Bl<double>(SkewTransform.CenterYProperty).Bl();
        (new Double2Bl(px, py)).Bind = Origin;

        var sx = skew.Bl<double>(SkewTransform.AngleXProperty).Bl().Degrees();
        var sy = skew.Bl<double>(SkewTransform.AngleYProperty).Bl().Degrees();
        return new DegreePointBl(sx, sy);
      }
      set {
        this.Skew.Bind = value;
      }
    }
     */

    /// <summary>
    /// Translate the UI element.
    /// </summary>
    public Double2Bl Translate {
      get {
        var trans = Transform<TranslateTransform>();
        var px = trans.Bl<double>(TranslateTransform.XProperty).Bl();
        var py = trans.Bl<double>(TranslateTransform.YProperty).Bl();
        return new Double2Bl(px, py);
      }
      set {
        this.Translate.Bind = value;
      }
    }
  }
  /// <summary>
  ///     Creates an arbitrary affine matrix transformation that is used to manipulate
  ///     objects or coordinate systems in a 2-D plane.
  /// </summary>
  public class MatrixTransformBl : TransformBl<MatrixTransform, MatrixTransformBl> {
    public MatrixTransformBl(Expr<MatrixTransform> Provider) : base(Provider) { }
    public MatrixTransformBl() : this(new Constant<MatrixTransform>(new MatrixTransform())) { }
    public static implicit operator MatrixTransformBl(Expr<MatrixTransform> v) { return new MatrixTransformBl(v); }
    public static implicit operator MatrixTransformBl(MatrixTransform v) { return new Constant<MatrixTransform>(v); }
    static MatrixTransformBl() {
    }
    /// <summary>
    ///     Gets or sets the System.Windows.Media.Matrix structure that defines this
    ///     transformation. This is a dependency property.
    /// Returns the System.Windows.Media.Matrix structure that defines this transformation.
    ///     The default value is an identity System.Windows.Media.Matrix. An identity
    ///     matrix has a value of 1 in coefficients [1,1], [2,2], and [3,3]; and a value
    ///     of 0 in the rest of the coefficients.
    /// </summary>
    public Matrix3Bl Matrix {
      get {
        var Core = Provider.Property<MatrixTransform,Matrix>(MatrixTransform.MatrixProperty);
        return Core.Bl();
      }
      set { Matrix.Bind = value; }
    }
  }


  /// <summary>
  ///     Paints an area with a solid color.
  /// </summary>
  public class SolidColorBrushBl : BrushBl<SolidColorBrush, SolidColorBrushBl> {
    public SolidColorBrushBl(Expr<SolidColorBrush> Provider) : base(Provider) { }
    public SolidColorBrushBl() : this(new Constant<SolidColorBrush>(new SolidColorBrush())) { }
    /// <summary>
    ///     Gets or sets the color of this System.Windows.Media.SolidColorBrush. This
    ///     is a dependency property. The default value is System.Windows.Media.Colors.Transparent.
    /// </summary>
    public ColorBl Color {
      get { return Provider.Property<SolidColorBrush,Color>(SolidColorBrush.ColorProperty); }
      set { Color.Bind = value; }
    }
    public static implicit operator SolidColorBrushBl(Expr<SolidColorBrush> v) { return new SolidColorBrushBl(v); }
    public static implicit operator SolidColorBrushBl(SolidColorBrush v) { return new Constant<SolidColorBrush>(v); }
  }
  /// <summary>
  ///     Paints an area with an image.
  /// </summary>
  public class ImageBrushBl : TileBrushBl<ImageBrush, ImageBrushBl> {
    public ImageBrushBl(Expr<ImageBrush> Provider) : base(Provider) { }
    public ImageBrushBl() : this(new Constant<ImageBrush>(new ImageBrush())) { }
    public ImageBrushBl(ImageSourceBl Source) : this() { ImageSource = Source; } 
    /// <summary>
    ///     Gets or sets the image displayed by this System.Windows.Media.ImageBrush.
    /// </summary>
    public ImageSourceBl ImageSource {
      get { return Provider.Property<ImageBrush,ImageSource>(ImageBrush.ImageSourceProperty).Bl(); }
      set { ImageSource.Bind = value; }
    }
    public static implicit operator ImageBrushBl(Expr<ImageBrush> v) { return new ImageBrushBl(v); }
    public static implicit operator ImageBrushBl(ImageBrush v) { return new Constant<ImageBrush>(v); }
    
  }
  /// <summary>
  ///     Paints an area with an image.
  /// </summary>
  public class VisualBrushBl : TileBrushBl<VisualBrush, VisualBrushBl> {
    public VisualBrushBl(Expr<VisualBrush> Provider) : base(Provider) { }
    public VisualBrushBl() : this(new Constant<VisualBrush>(new VisualBrush())) { }
    /// <summary>
    ///     Gets or sets the brush's content. This is a dependency property.
    ///     Returns the brush's content. The default is null.
    /// </summary>
    public VisualBl Visual {
      get { return Provider.Property<VisualBrush,Visual>(VisualBrush.VisualProperty); }
      set { Visual.Bind = value; }
    }
    public static implicit operator VisualBrushBl(Expr<VisualBrush> v) { return new VisualBrushBl(v); }
    public static implicit operator VisualBrushBl(VisualBrush v) { return new Constant<VisualBrush>(v); }
  }


  /// <summary>
  ///     Abstract class that describes a 2-D drawing. 
  /// </summary>
  public class DrawingBl<T,BRAND> : Brand<T,BRAND>, IExtends<BRAND,DrawingBl> where T : Drawing where BRAND : DrawingBl<T,BRAND> {
    static DrawingBl() { DrawingBl.CheckInit(); }
    public DrawingBl(Expr<T> v) : base(v) { }
    public static implicit operator DrawingBl(DrawingBl<T, BRAND> b) {
      return DrawingBl.UpCast(b);
    }
  }

  /// <summary>
  ///     Abstract class that describes a 2-D drawing. 
  /// </summary>
  public class DrawingBl : DrawingBl<Drawing, DrawingBl> {
    public DrawingBl(Expr<Drawing> v) : base(v) { }
    public static implicit operator DrawingBl(Expr<Drawing> v) { return new DrawingBl(v); }
    public static implicit operator DrawingBl(Drawing d) { return new Constant<Drawing>(d); }
    public static void CheckInit() { Extensions.Trace("CheckInit: " + typeof(DrawingBl) + " ToBrand=" + ToBrand); }
  }
  /// <summary>
  ///     Draws a System.Windows.Media.Geometry using the specified System.Windows.Media.GeometryDrawing.Brush
  ///     and System.Windows.Media.GeometryDrawing.Pen.
  /// </summary>
  public class GeometryDrawingBl : DrawingBl<GeometryDrawing, GeometryDrawingBl> {
    public GeometryDrawingBl(Expr<GeometryDrawing> v) : base(v) {
      typeof(GeometryBl).GetHashCode();
    }
    public GeometryDrawingBl() : base(new Constant<GeometryDrawing>(new GeometryDrawing())) { }
    public static implicit operator GeometryDrawingBl(Expr<GeometryDrawing> v) { return new GeometryDrawingBl(v); }
    public static implicit operator GeometryDrawingBl(GeometryDrawing d) { return new Constant<GeometryDrawing>(d); }
    /// <summary>
    ///     Gets or sets the System.Windows.Media.Brush used to fill the interior of
    ///     the shape described by this System.Windows.Media.GeometryDrawing. This is
    ///     a dependency property. The default
    ///     value is null.
    /// </summary>
    public BrushBl Brush {
      get { return Provider.Property<GeometryDrawing,Brush>(GeometryDrawing.BrushProperty); }
      set { Brush.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the System.Windows.Media.Geometry that describes the shape of
    ///     this System.Windows.Media.GeometryDrawing. This is a dependency property. The default
    ///     value is null.
    /// </summary>
    public GeometryBl Geometry {
      get { return Provider.Property<GeometryDrawing, Geometry>(GeometryDrawing.GeometryProperty); }
      set { Geometry.Bind = value; }
    }

    public PenBl Pen {
      get { return Provider.Property<GeometryDrawing, Pen>(GeometryDrawing.PenProperty); }
      set { Pen.Bind = value; }
    }
  }
  /// <summary>
  ///     Represents the sequence of dashes and gaps that will be applied by a System.Windows.Media.Pen.
  /// </summary>
  public class DashStyleBl : Brand<DashStyle, DashStyleBl> {
    public DashStyleBl(Expr<DashStyle> v) : base(v) { }
    public DashStyleBl() : this(new Constant<DashStyle>(new DashStyle())) { }
    public static implicit operator DashStyleBl(Expr<DashStyle> v) { return new DashStyleBl(v); }
    public static implicit operator DashStyleBl(DashStyle d) { return new Constant<DashStyle>(d); }

    /// <summary>
    ///     Gets or sets the collection of dashes and gaps in this System.Windows.Media.DashStyle.
    ///     This is a dependency property. The default is an empty System.Windows.Media.DoubleCollection.
    /// </summary>
    public DoubleCollectionBl Dashes {
      get { return Provider.Property<DashStyle,DoubleCollection>(DashStyle.DashesProperty); }
      set { Dashes.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets how far in the dash sequence the stroke will start. This is
    ///     a dependency property.
    ///     The offset for the dash sequence. The default is 0.
    /// </summary>
    public DoubleBl Offset {
      get { return Provider.Property<DashStyle,double>(DashStyle.OffsetProperty); }
      set { Offset.Bind = value; }
    }
  }

  /// <summary>
  ///     Describes how a shape is outlined.
  /// </summary>
  public class PenBl : Brand<Pen, PenBl> {
    public PenBl(Expr<Pen> v) : base(v) { }
    public PenBl() : this(new Constant<Pen>(new Pen())) { }
    public static implicit operator PenBl(Expr<Pen> v) { return new PenBl(v); }
    public static implicit operator PenBl(Pen d) { return new Constant<Pen>(d); }

    /// <summary>
    ///     Gets or sets the fill the outline produced by this System.Windows.Media.Pen.
    ///     This is a dependency property. The default
    ///     value is null.
    /// </summary>
    public BrushBl Brush {
      get { return Provider.Property<Pen,Brush>(Pen.BrushProperty); }
      set { Brush.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value that describes the pattern of dashes generated by this
    ///     System.Windows.Media.Pen. This is a dependency property.
    ///     A value that describes the pattern of dashes generated by this System.Windows.Media.Pen.
    ///     The default is System.Windows.Media.DashStyles.Solid, which indicates that
    ///     there should be no dashes.
    /// </summary>
    public DashStyleBl DashStyle {
      get { return Provider.Property<Pen,DashStyle>(Pen.DashStyleProperty); }
      set { DashStyle.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value that specifies how the ends of each dash are drawn.
    ///     This is a dependency property. This setting applies to both
    ///     ends of each dash. The default value is System.Windows.Media.PenLineCap.Flat.
    /// </summary>
    public EnumBl<PenLineCap> DashCap {
      get { return Provider.Property<Pen,PenLineCap>(Pen.DashCapProperty); }
      set { DashCap.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the type of shape to use at the end of a stroke. This is a dependency
    ///     property. The type of shape that ends the stroke. The default value is System.Windows.Media.PenLineCap.Flat.
    /// </summary>
    public EnumBl<PenLineCap> EndLineCap {
      get { return Provider.Property<Pen, PenLineCap>(Pen.EndLineCapProperty); }
      set { EndLineCap.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the type of shape to use at the beginning of a stroke. This
    ///     is a dependency property. The type of shape that starts the stroke. The default value is System.Windows.Media.PenLineCap.Flat.
    /// </summary>
    public EnumBl<PenLineCap> StartLineCap {
      get { return Provider.Property<Pen, PenLineCap>(Pen.StartLineCapProperty); }
      set { StartLineCap.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the type of joint used at the vertices of a shape's outline.
    ///     This is a dependency property. The type of joint used at the vertices of a shape's outline. The default
    ///     value is System.Windows.Media.PenLineJoin.Miter.
    /// </summary>
    public EnumBl<PenLineJoin> LineJoin {
      get { return Provider.Property<Pen, PenLineJoin>(Pen.LineJoinProperty); }
      set { LineJoin.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the limit on the ratio of the miter length to half this pen's
    ///     System.Windows.Media.Pen.Thickness. This is a dependency property.
    ///     The limit on the ratio of the miter length to half the pen's System.Windows.Media.Pen.Thickness.
    ///     This value is always a positive number greater than or equal to 1. The default
    ///     value is 10.0.
    /// </summary>
    public DoubleBl MiterLimit {
      get { return Provider.Property<Pen, double>(Pen.MiterLimitProperty); }
      set { MiterLimit.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the thickness of the stroke produced by this System.Windows.Media.Pen.
    ///     This is a dependency property. The thickness of the stroke produced by this System.Windows.Media.Pen. Default
    ///     is 1.
    /// </summary>
    public DoubleBl Thickness {
      get { return Provider.Property<Pen, double>(Pen.ThicknessProperty); }
      set { Thickness.Bind = value; }
    }
  }


  /// <summary>
  ///     Classes that derive from this abstract base class define geometric shapes.
  ///     System.Windows.Media.Geometry objects can be used for clipping, hit-testing,
  ///     and rendering 2-D graphic data.
  /// </summary>
  public class GeometryBl : GeometryBl<Geometry, GeometryBl> {
    public GeometryBl(Expr<Geometry> v) : base(v) { }
    public GeometryBl() : base() { }
    public static implicit operator GeometryBl(Expr<Geometry> v) { return new GeometryBl(v); }
    public static implicit operator GeometryBl(Geometry d) { return new Constant<Geometry>(d); }
    static GeometryBl() {
    }


    /// <summary>
    /// Creat a line geometry.
    /// </summary>
    /// <param name="Start">Start point of line.</param>
    /// <param name="End">End point of line.</param>
    public static GeometryBl Line(Double2Bl Start, Double2Bl End) {
      var ret = new LineGeometry();
      ret.Bl<Point>(LineGeometry.StartPointProperty).Bl().Bind = Start;
      ret.Bl<Point>(LineGeometry.  EndPointProperty).Bl().Bind = End;
      return new GeometryBl(new Constant<Geometry>(ret));
    }
    /// <summary>
    /// Create an ellipse geometry.
    /// </summary>
    /// <param name="Center">Center point of geometry.</param>
    /// <param name="Radius">XY radii of ellipse.</param>
    /// <returns></returns>
    public static GeometryBl Ellipse(Double2Bl Center, Double2Bl Radius) {
      var ret = new EllipseGeometry();
      ret.Bl<Point>(EllipseGeometry.CenterProperty).Bl().Bind = Center;
      ret.Bl<double>(EllipseGeometry.RadiusXProperty).Bl().Bind = Radius.X;
      ret.Bl<double>(EllipseGeometry.RadiusYProperty).Bl().Bind = Radius.Y;
      return new GeometryBl(new Constant<Geometry>(ret));
    }
    /// <summary>
    /// Create a circle geometry.
    /// </summary>
    /// <param name="Center">Center point of circle.</param>
    /// <param name="Radius">Radius of circle.</param>
    /// <returns></returns>
    public static GeometryBl Circle(Double2Bl Center, DoubleBl Radius) {
      return Ellipse(Center, new Double2Bl(Radius, Radius));
    }
    /// <summary>
    /// Create a rectangle geometry.
    /// </summary>
    /// <param name="LeftTop">Left-top point of rectangle.</param>
    /// <param name="Size">Size of rectangle.</param>
    /// <param name="Radius">XY radius of curved corners (0 if no curves desired)</param>
    public static GeometryBl Rectangle(Double2Bl LeftTop, Double2Bl Size, Double2Bl Radius) {
      var ret = new RectangleGeometry();
      Double4Bl Rect = ret.Bl<Rect>(RectangleGeometry.RectProperty);
      Rect.Bind = new Double4Bl(LeftTop, Size);
      ret.Bl<double>(RectangleGeometry.RadiusXProperty).Bl().Bind = Radius.X;
      ret.Bl<double>(RectangleGeometry.RadiusYProperty).Bl().Bind = Radius.Y;
      return new GeometryBl(new Constant<Geometry>(ret));
    }
    /// <summary>
    /// Create a rectangle geometry with non-curved corners.
    /// </summary>
    /// <param name="LeftTop">Left-top point of rectangle.</param>
    /// <param name="Size">Size of rectangle.</param>
    public static GeometryBl Rectangle(Double2Bl LeftTop, Double2Bl Size) {
      return Rectangle(LeftTop, Size, 0);
    }
    /// <summary>
    /// Create a rectangle geometry with uniformed-curved corners.
    /// </summary>
    /// <param name="LeftTop">Left-top point of rectangle.</param>
    /// <param name="Size">Size of rectangle.</param>
    /// <param name="Radius">Radius of curved corners (0 if no curves desired)</param>
    public static GeometryBl Rectangle(Double2Bl LeftTop, Double2Bl Size, DoubleBl Radius) {
      return Rectangle(LeftTop, Size, new Double2Bl(Radius, Radius));
    }
    /// <summary>
    /// Create a square geometry.
    /// </summary>
    /// <param name="LeftTop">Left top point of square.</param>
    /// <param name="Size">Width and height of square.</param>
    public static GeometryBl Square(Double2Bl LeftTop, DoubleBl Size) {
      return Rectangle(LeftTop, new Double2Bl(Size, Size));
    }
  }
  /// <summary>
  ///     Describes a way to paint a region by using one or more tiles.
  /// </summary>
  public abstract class TileBrushBl<T,SELF> : BrushBl<T,SELF> where T : TileBrush where SELF : TileBrushBl<T,SELF> {
    public TileBrushBl(Expr<T> Provider) : base(Provider) { }
    public class AlignmentSet {
      internal Expr<T> Underlying;
      /// <summary>
      ///     A value that specifies the horizontal position of System.Windows.Media.TileBrush
      ///     content in its base tile. The default value is System.Windows.HorizontalAlignment.Center.
      /// </summary>
      public EnumBl<AlignmentX> X {
        get { return Underlying.Property<T,AlignmentX>(TileBrush.AlignmentXProperty); }
        set { X.Bind = value; }
      }
      /// <summary>
      ///     A value that specifies the vertical position of System.Windows.Media.TileBrush
      ///     content in its base tile. The default value is System.Windows.Media.AlignmentY.Center.
      /// </summary>
      public EnumBl<AlignmentY> Y {
        get { return Underlying.Property<T,AlignmentY>(TileBrush.AlignmentYProperty); }
        set { Y.Bind = value; }
      }
      internal AlignmentSet Bind {
        set { X = value.X; Y = value.Y; }
      }
    }
    /// <summary>
    ///     The alignment of System.Windows.Media.TileBrush
    ///     content in its base tile. The default value is Center, Center.
    /// </summary>
    public AlignmentSet Alignment {
      get { return new AlignmentSet() { Underlying = Provider }; }
      set { Alignment.Bind = value; }
    }
    /// <summary>
    ///     A value that specifies how this System.Windows.Media.TileBrush content is
    ///     projected onto its base tile. The default value is System.Windows.Media.Stretch.Fill.
    /// </summary>
    public EnumBl<Stretch> Stretch {
      get { return Provider.Property<T,Stretch>(TileBrush.StretchProperty); }
      set { Stretch.Bind = value; }
    }
    /// <summary>
    ///     A value that specifies how the System.Windows.Media.TileBrush tiles fill
    ///     the output area when the base tile, which is specified by the System.Windows.Media.TileBrush.Viewport
    ///     property, is smaller than the output area. The default value is System.Windows.Media.TileMode.None.
    /// </summary>
    public EnumBl<TileMode> TileMode {
      get { return Provider.Property<T,TileMode>(TileBrush.TileModeProperty); }
      set { TileMode.Bind = value; }
    }
    /// <summary>
    /// Dimensions and units for the TileBrushe's base tile (Port) and tile content (Box).
    /// </summary>
    public ViewSet View {
      get { return new ViewSet() { Underlying = Provider }; }
      set { View.Bind = value; }
    }
    public class ViewSet {
      internal Expr<T> Underlying;
      /// <summary>
      /// Dimensions and units for the TileBrush's base tile.
      /// </summary>
      public ElementSet Port {
        get { return new ElementSet() { Underlying = Underlying, DimProperty = TileBrush.ViewportProperty, UnitsProperty = TileBrush.ViewportUnitsProperty }; }
        set { Port.Bind = value; }
      }
      /// <summary>
      /// Dimensions and units for the content of a tile in the TileBrush.
      /// </summary>
      public ElementSet Box {
        get { return new ElementSet() { Underlying = Underlying, DimProperty = TileBrush.ViewboxProperty, UnitsProperty = TileBrush.ViewboxUnitsProperty }; }
        set { Box.Bind = value; }
      }
      public class ElementSet {
        internal Expr<T> Underlying;
        internal DependencyProperty DimProperty;
        internal DependencyProperty UnitsProperty;
        /// <summary>
        //     The position and dimensions of view.
        //     The default value is a rectangle (System.Windows.Rect) with a System.Windows.Rect.TopLeft
        //     of (0,0) and a System.Windows.Rect.Width and System.Windows.Rect.Height of
        //     1.
        /// </summary>
        public Double4Bl Dim {
          get { return Underlying.Property<T,Rect>(DimProperty); }
          set { Dim.Bind = value;  }
        }
        /// <summary>
        ///     Indicates whether the value of the view is relative to the size of the whole output area. The default value
        ///     is System.Windows.Media.BrushMappingMode.RelativeToBoundingBox.
        /// </summary>
        public EnumBl<BrushMappingMode> Units {
          get { return Underlying.Property<T,BrushMappingMode>(UnitsProperty); }
          set { Units.Bind = value; }
        }
        internal ElementSet Bind {
          set { Dim = value.Dim; Units = value.Units; }
        }
      }
      internal ViewSet Bind {
        set { Port = value.Port; Box = value.Box; }
      }
    }
  }
  public class DrawingBrushBl : TileBrushBl<DrawingBrush, DrawingBrushBl> {
    public DrawingBrushBl(Expr<DrawingBrush> Provider) : base(Provider) { }
    public DrawingBrushBl() : this(new Constant<DrawingBrush>(new DrawingBrush())) { }
    public DrawingBl Drawing {
      get { return Provider.Property<DrawingBrush,Drawing>(DrawingBrush.DrawingProperty); }
      set { Drawing.Bind = value; }
    }
    public static implicit operator DrawingBrushBl(Expr<DrawingBrush> v) { return new DrawingBrushBl(v); }

    static DrawingBrushBl() {
    }
  }

  public abstract class GradientBrushBl<T,SELF> : BrushBl<T,SELF> where T : GradientBrush where SELF : GradientBrushBl<T,SELF> {
    public GradientBrushBl(Expr<T> Provider) : base(Provider) { }
    /// <summary>
    /// Gets or sets a System.Windows.Media.ColorInterpolationMode enumeration that
    ///     specifies how the gradient's colors are interpolated.
    /// </summary>
    public EnumBl<ColorInterpolationMode> ColorInterpolationMode {
      get { return Provider.Property<T,ColorInterpolationMode>(GradientBrush.ColorInterpolationModeProperty); }
      set { ColorInterpolationMode.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the type of spread method that specifies how to draw a gradient
    ///     that starts or ends inside the bounds of the object to be painted.
    /// </summary>
    public EnumBl<GradientSpreadMethod> SpreadMethod {
      get { return Provider.Property<T,GradientSpreadMethod>(GradientBrush.SpreadMethodProperty); }
      set { SpreadMethod.Bind = value; }
    }
    /// <summary>
    /// Gets or sets a System.Windows.Media.BrushMappingMode enumeration that specifies
    ///     whether the gradient brush's positioning coordinates are absolute or relative
    ///     to the output area. 
    /// </summary>
    public EnumBl<BrushMappingMode> MappingMode {
      get { return Provider.Property<T,BrushMappingMode>(GradientBrush.MappingModeProperty); }
      set { MappingMode.Bind = value; } 
    }
    /// <summary>
    /// Describes the location and color of a transition point in a gradient
    /// </summary>
    /// <param name="color">the color of the gradient stop</param>
    /// <param name="offset">the location of the gradient stop within the gradient vector</param>
    /// <returns></returns>
    public SELF Stop(ColorBl color, DoubleBl offset) {
      var target = (GradientBrush)Provider.CurrentValue;
      var stop = new GradientStop();
      
      stop.Bl<Color>(GradientStop.ColorProperty).Bl().Bind = color;
      stop.Bl<double>(GradientStop.OffsetProperty).Bl().Bind = offset;
      target.GradientStops.Add(stop);
      return this;
    }
  }
  /// <summary>
  ///   Paints an area with a linear gradient.
  /// </summary>
  public class LinearGradientBrushBl : GradientBrushBl<LinearGradientBrush, LinearGradientBrushBl> {
    public LinearGradientBrushBl(Expr<LinearGradientBrush> Provider) : base(Provider) { }
    public LinearGradientBrushBl() : this(new Constant<LinearGradientBrush>(new LinearGradientBrush())) { }
    static LinearGradientBrushBl() {
    }
    public static implicit operator LinearGradientBrushBl(Expr<LinearGradientBrush> v) { return new LinearGradientBrushBl(v); }

    /// <summary>
    /// Gets or sets the starting two-dimensional coordinates of the linear gradient.
    /// </summary>
    public Double2Bl StartPoint {
      get { return Provider.Property<LinearGradientBrush, Point>(LinearGradientBrush.StartPointProperty); }
      set { StartPoint.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the ending two-dimensional coordinates of the linear gradient.
    /// </summary>
    public Double2Bl EndPoint {
      get { return Provider.Property<LinearGradientBrush, Point>(LinearGradientBrush.EndPointProperty); }
      set { EndPoint.Bind = value; }
    }

  }
  /// <summary>
  /// Paints an area with a radial gradient. A focal point defines the beginning
  ///     of the gradient, and a circle defines the end point of the gradient.
  /// </summary>
  public class RadialGradientBrushBl : GradientBrushBl<RadialGradientBrush, RadialGradientBrushBl> {
    public RadialGradientBrushBl(Expr<RadialGradientBrush> Provider) : base(Provider) { }
    public RadialGradientBrushBl() : this(new Constant<RadialGradientBrush>(new RadialGradientBrush())) { }
    static RadialGradientBrushBl() {
    }
    public static implicit operator RadialGradientBrushBl(Expr<RadialGradientBrush> v) { return new RadialGradientBrushBl(v); }

    /// <summary>
    /// Gets or sets the center of the outermost circle of the radial gradient.
    /// </summary>
    public Double2Bl Center {
      get { return Provider.Property<RadialGradientBrush, Point>(RadialGradientBrush.CenterProperty); }
      set { Center.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the location of the two-dimensional focal point that defines
    ///     the beginning of the gradient.
    /// </summary>
    public Double2Bl GradientOrigin {
      get { return Provider.Property<RadialGradientBrush, Point>(RadialGradientBrush.GradientOriginProperty); }
        set { GradientOrigin.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the radius of the outermost circle of the radial gradient.
    /// </summary>
    public Double2Bl Radius {
      get {
        var x = Provider.Property<RadialGradientBrush, double>(RadialGradientBrush.RadiusXProperty);
        var y = Provider.Property<RadialGradientBrush, double>(RadialGradientBrush.RadiusYProperty);
        return new Double2Bl(x, y);
      }
      set { Radius.Bind = value; }
    }
  }
  public sealed partial class FrameworkElementBl : FrameworkElementBl<FrameworkElement, FrameworkElementBl> {
    internal static readonly GetProperty<FrameworkElement, double> CenterRotationProperty = 
      "CenterRotation".NewProperty<FrameworkElement, double>();
    internal static readonly GetProperty<FrameworkElement, Point> CenterScaleProperty = 
      "CenterScale".NewProperty<FrameworkElement, Point>();
    internal static readonly GetProperty<FrameworkElement, object> DragAdapterProperty = 
      "DragAdapter".NewProperty<FrameworkElement, object>(null);



    /// <summary>
    /// Create a dependency property to represent the canvas owner of a framework element.
    /// </summary>
    internal static readonly GetProperty<FrameworkElement, Panel> PanelParentProperty =
      "PanelParent".NewProperty<FrameworkElement, Panel>(null, (element, oldV, newV) => {
        if (oldV != null) {
          oldV.Children.Remove(element);
        }
        if (newV != null) newV.Children.Add(element);
      });

    public FrameworkElementBl(Expr<FrameworkElement> Provider) : base(Provider) { }
    public FrameworkElementBl() : base() { }
    static FrameworkElementBl() {
    }
    public static implicit operator FrameworkElementBl(Expr<UIElement> v) {
      return Ops.DownCastOperator<UIElement, FrameworkElement>.Instance.Make(v);
    }
    public static implicit operator FrameworkElementBl(Expr<FrameworkElement> v) { return new FrameworkElementBl(v); }
    public static implicit operator FrameworkElementBl(FrameworkElement e) {
      return new Constant<FrameworkElement>(e);
    }
  }
  /// <summary>
  //     Provides a WPF framework-level set of properties, events, and methods for
  //     Windows Presentation Foundation (WPF) elements. This class represents the
  //     provided WPF framework-level implementation built on the WPF core-level APIs
  //     defined by System.Windows.UIElement.
  /// </summary>
  public abstract partial class FrameworkElementBl<T,BRAND> : UIElementBl<T,BRAND>, IExtends<BRAND,FrameworkElementBl> 
    where T : FrameworkElement
    where BRAND : FrameworkElementBl<T,BRAND> {


    public FrameworkElementBl(Expr<T> Provider) : base(Provider) { }
    public FrameworkElementBl() : base() { }
    public FrameworkElementBl(PanelBl Panel, T Target)
      : this(new Constant<T>(Target)) {
      //(((object)canvas) ).CheckInit();
      this.PanelParent = Panel;
    }
    /// <summary>
    ///     Occurs when the element is laid out, rendered, and ready for interaction.
    /// </summary>
    public EventStream Loaded {
      get {
        return new DefaultEventStream<RoutedEventHandler>() {
          Transform = a => (x, y) => a(),
          Add = a => CurrentValue.Loaded += a,
          Remove = a => CurrentValue.Loaded -= a,
        };
      }
    }



    public Double2Bl ScaleTo {
      set {
        var sz = value / Size;
        this.RenderTransform.ScaleXY = sz.X.Min(sz.Y);
      }
    }
    public static implicit operator T(FrameworkElementBl<T, BRAND> self) { return self.CurrentValue; }    
    
    public static implicit operator FrameworkElementBl(FrameworkElementBl<T, BRAND> self) {      
      var ret = FrameworkElementBl.UpCast((Brand<BRAND>) self);
      return ret;
    }    
    public static implicit operator Expr<FrameworkElement>(FrameworkElementBl<T, BRAND> self) {
      FrameworkElementBl b = self;
      return b.Provider;
    }
    /// <summary>
    ///     Gets or sets a value indicating whether to clip the content of this element
    ///     (or content coming from the child elements of this element) to fit into the
    ///     size of the containing element. This is a dependency property.
    /// </summary>
    public BoolBl ClipToBounds {
      get { return Provider.Property<T,bool>(UIElement.ClipToBoundsProperty); }
      set { ClipToBounds.Bind = value; }
    }

    /// <summary>
    ///     Gets or sets the geometry used to define the outline of the contents of an
    ///     element. This is a dependency property.
    /// </summary>
    public GeometryBl Clip {
      get { return Provider.Property<T,Geometry>(UIElement.ClipProperty); }
      set { Clip.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value that determines whether rendering for this element should
    ///     use device-specific pixel settings during rendering. This is a dependency
    ///     property.
    /// </summary>
    public BoolBl SnapsToDevicePixels {
      get { return Provider.Property<T,bool>(UIElement.SnapsToDevicePixelsProperty); }
      set { SnapsToDevicePixels.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets an opacity mask, as a System.Windows.Media.Brush implementation
    ///     that is applied to any alpha-channel masking for the rendered content of
    ///     this element.
    /// </summary>
    public BrushBl OpacityMask {
      get { return Provider.Property<T,Brush>(FrameworkElement.OpacityMaskProperty); }
      set { OpacityMask.Bind = value; }
    }


    public class AlignmentSet {
      internal Expr<T> Underlying;
      internal DependencyProperty HorizontalAlignmentProperty;
      internal DependencyProperty VerticalAlignmentProperty;

      /// <summary>
      ///     Gets or sets horizontal alignment. 
      /// </summary>
      public EnumBl<HorizontalAlignment> Horizontal {
        get { return Underlying.Property<T,HorizontalAlignment>(HorizontalAlignmentProperty); }
        set { Horizontal.Bind = value; }
      }
      /// <summary>
      ///     Gets or sets vertical alignment. 
      /// </summary>
      public EnumBl<VerticalAlignment> Vertical {
        get { return Underlying.Property<T,VerticalAlignment>(VerticalAlignmentProperty); }
        set { Vertical.Bind = value; }
      }
      internal AlignmentSet Bind {
        set {
          this.Horizontal.Bind = value.Horizontal;
          this.Vertical.Bind = value.Vertical;
        }
      }
    }
    /// <summary>
    /// Gets or sets the alignment characteristics applied to this element
    /// when it is composed within a parent element, such as a panel or items control.
    /// Default is Horizontal and Vertical Stretch.
    /// </summary>
    public AlignmentSet Alignment {
      get { return new AlignmentSet() { Underlying = Provider, HorizontalAlignmentProperty = FrameworkElement.HorizontalAlignmentProperty, VerticalAlignmentProperty = FrameworkElement.VerticalAlignmentProperty }; }
      set { Alignment.Bind = (value); }
    }
    /// <summary>
    ///     Gets or sets a value indicating whether this element is enabled in the user
    ///     interface (UI). This is a dependency property.
    /// </summary>
    /// <returns>
    ///     true if the element is enabled; otherwise, false. The default value is true.
    ///</returns>
    public BoolBl IsEnabled {
      get { return Provider.Property<T,bool>(FrameworkElement.IsEnabledProperty); }
      set { IsEnabled.Bind = value; }
    }
    /// <summary>
    ///    Gets or sets a value that declares whether this element can possibly be returned
    ///     as a hit test result from some portion of its rendered content.
    /// </summary>
    public BoolBl IsHitTestVisible {
      get { return Provider.Property<T,bool>(FrameworkElement.IsHitTestVisibleProperty); }
      set { IsHitTestVisible.Bind = value; }
    }

    /// <summary>
    ///     Gets a value that determines whether this element has logical focus. This
    ///     is a dependency property.
    /// </summary>
    /// <returns>
    ///     true if this element has logical focus; otherwise, false.
    ///</returns>
    public BoolBl IsFocused {
      get { return Provider.Property<T,bool>(FrameworkElement.IsFocusedProperty); }
    }
    /// <summary>
    ///    Gets a value indicating whether the mouse pointer is located over this element
    ///     (including child elements in the visual tree). This is a dependency property.
    /// </summary>
    /// <returns>
    ///     true if mouse pointer is over the element or its child elements; otherwise,
    ///     false. The default is false. 
    ///</returns>
    public BoolBl IsMouseOver {
      get { return Provider.Property<T,bool>(FrameworkElement.IsMouseOverProperty); }
    }
    /// <summary>
    /// Set a mouse enter handler. First argument is current widget, second argument is 
    /// mouse event arguments. Return true if you want the handler to remain installed, 
    /// else return false to uninstall this handler.
    /// </summary>
    public Func<BRAND, System.Windows.Input.MouseEventArgs, bool> OnMouseEnter {
      set {
        System.Windows.Input.MouseEventHandler F = null;
        F = (x, y) => {
          if (!value(FrameworkElementBl<T, BRAND>.ToBrand(new Constant<T>((T)x)), y))
            CurrentValue.MouseEnter -= F;
        };
        CurrentValue.MouseEnter += F;
      }
    }
    /// <summary>
    /// Set a mouse leave handler. First argument is current widget, second argument is 
    /// mouse event arguments. Return true if you want the handler to remain installed, 
    /// else return false to uninstall this handler.
    /// </summary>
    public Func<BRAND, System.Windows.Input.MouseEventArgs, bool> OnMouseLeave {
      set {
        System.Windows.Input.MouseEventHandler F = null;
        F = (x, y) => {
          if (!value(FrameworkElementBl<T, BRAND>.ToBrand(new Constant<T>((T)x)), y))
            CurrentValue.MouseLeave -= F;
        };
        CurrentValue.MouseLeave += F;
      }
    }
    /// <summary>
    /// Set a mouse down handler. First argument is current widget, second argument is 
    /// mouse event arguments. Return true if you want the handler to remain installed, 
    /// else return false to uninstall this handler.
    /// </summary>
    public Func<BRAND, System.Windows.Input.MouseButtonEventArgs, bool> OnMouseDown {
      set {
        System.Windows.Input.MouseButtonEventHandler F = null;
        F = (x, y) => {
          if (!value(FrameworkElementBl<T, BRAND>.ToBrand(new Constant<T>((T)x)), y))
            CurrentValue.MouseDown -= F;
        };
        CurrentValue.MouseDown += F;
      }
    }

    public void InstallDragHandler(Func<bool> Start, Action Move, Action Finish) {
      var IsGoing = false;
      OnMouseDown = (self, e) => {
        if (IsGoing) { // glitch?
          IsGoing = false;
          Finish();
          System.Windows.Input.Mouse.Capture(self.CurrentValue, CaptureMode.None);
        }
        if (!Start()) return false;
        e.Handled = true;
        IsGoing = true;
        System.Windows.Input.Mouse.Capture(self.CurrentValue, CaptureMode.Element);
        self.OnMouseUp = (self0, e0) => {
          if (IsGoing) {
            IsGoing = false;
            Finish();
            System.Windows.Input.Mouse.Capture(self0.CurrentValue, CaptureMode.None);
            e0.Handled = true;
          }
          return false;
        };
        self.OnMouseMove = (self0, e0) => {
          if (!IsGoing) return false;
          e0.Handled = true;
          if (System.Windows.Input.Mouse.LeftButton != MouseButtonState.Pressed) {
            IsGoing = false;
            Finish();
            System.Windows.Input.Mouse.Capture(self0.CurrentValue, CaptureMode.None);
            return false;
          }
          Move();
          return true;
        };
        return true;
      };
    }
    /// <summary>
    /// Set a mouse up handler. First argument is current widget, second argument is 
    /// mouse event arguments. Return true if you want the handler to remain installed, 
    /// else return false to uninstall this handler.
    /// </summary>
    public Func<BRAND, System.Windows.Input.MouseButtonEventArgs, bool> OnMouseUp {
      set {
        System.Windows.Input.MouseButtonEventHandler F = null;
        F = (x, y) => {
          if (!value(FrameworkElementBl<T, BRAND>.ToBrand(new Constant<T>((T)x)), y))
            CurrentValue.MouseUp -= F;
        };
        CurrentValue.MouseUp += F;
      }
    }
    /// <summary>
    /// Set a mouse move handler. First argument is current widget, second argument is 
    /// mouse event arguments. Return true if you want the handler to remain installed, 
    /// else return false to uninstall this handler.
    /// </summary>
    public Func<BRAND, System.Windows.Input.MouseEventArgs, bool> OnMouseMove {
      set {
        System.Windows.Input.MouseEventHandler F = null;
        F = (x, y) => {
          if (!value(FrameworkElementBl<T, BRAND>.ToBrand(new Constant<T>((T)x)), y))
            CurrentValue.MouseMove -= F;
        };
        CurrentValue.MouseMove += F;
      }
    }



    /// <summary>
    ///    Gets a value indicating whether this element is visible in the user interface
    ///     (UI). This is a dependency property.
    /// </summary>
    /// <returns>
    ///     true if the element is visible; otherwise, false.
    ///</returns>
    public BoolBl IsVisible {
      get { return Provider.Property<T,bool>(FrameworkElement.IsVisibleProperty); }
    }
    /// <summary>
    ///     Gets or sets the user interface (UI) visibility of this element. This is
    ///     a dependency property.
    /// </summary>
    /// <returns>
    ///     A value of the enumeration. The default value is System.Windows.Visibility.Visible.
    ///</returns>
    public VisibilityBl Visibility {
      get { return Provider.Property<T,Visibility>(FrameworkElement.VisibilityProperty); }
      set { Visibility.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the opacity factor applied to the entire System.Windows.UIElement
    ///     when it is rendered in the user interface (UI). This is a dependency property.
    /// </summary>
    /// <returns>
    ///     The opacity factor. Default opacity is 1.0. Expected values are between 0.0
    ///     and 1.0.
    ///</returns>
    public DoubleBl Opacity {
      get { return Provider.Property<T,double>(FrameworkElement.OpacityProperty); }
      set { Opacity.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the identifying name of the element. The name provides a reference
    ///     so that code-behind, such as event handler code, can refer to a markup element
    ///     after it is constructed during processing by a XAML processor. This is a
    ///     dependency property.
    /// </summary>
    /// <returns>
    ///    The name of the element. The default is an empty string.
    ///</returns>
    public StringBl Name {
      get { return Provider.Property<T,string>(FrameworkElement.NameProperty); }
      set { Name.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the tool-tip object that is displayed for this element in the
    ///     user interface (UI). This is a dependency property.
    /// </summary>
    /// <returns>
    ///    The tooltip object. See returns below for details on why this parameter is
    ///     not strongly typed.
    ///</returns>
    public ObjectBl ToolTip {
      get { return Provider.Property<T,object>(FrameworkElement.ToolTipProperty); }
      set { ToolTip.Bind = value; }
    }
    /// <summary>
    /// A special parent property that will manage adding/removing this UI element from a canvas. 
    /// When set to a canvas, the element will be added to that canvas, when unset, the element will be removed
    /// from the canvas. 
    /// </summary>
    public PanelBl PanelParent {
      get {
        return FrameworkElementBl.PanelParentProperty[this].Bl();
      }
      set {
        PanelParent.Bind = value; 
      }
    }
    /// <summary>
    /// This element's logical parent.
    /// </summary>
    public FrameworkElementBl Parent {
      get {
        return this.Map<FrameworkElement, FrameworkElementBl>(value => {
          return (FrameworkElement)value.Parent;
        });
      }
    }
    [Obsolete("Use CanvasParent = CanvasBl.None instead.")]
    public void Remove() {
      this.PanelParent =((PanelBl) null);
    }
    /// <summary>
    /// Gets or sets the UI element's left position.
    /// </summary>
    public virtual DoubleBl Left {
      get {
        return Provider.Property<T,double>(Canvas.LeftProperty).Bl();
      }
      set { Left.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's top position.
    /// </summary>
    public virtual DoubleBl Top
    {
      get {
        return Provider.Property<T,double>(Canvas.TopProperty).Bl();
      }
      set { Top.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's width. 
    /// </summary>
    public DoubleBl Width {
      get {
        return Provider.Property<T,double>(FrameworkElement.ActualWidthProperty, FrameworkElement.WidthProperty).Bl(); // .Restrict(0, double.MaxValue);
      }
      set { Width.Bind = value.Max(0d); }
    }

    public ObjectBl Tag {
      get {
        return (Provider.Property<T,object>(FrameworkElement.TagProperty)); 
      }
      set { Tag.Bind = value; }
    }

    /// <summary>
    /// Gets or sets the UI element's height.
    /// </summary>
    public DoubleBl Height {
      get {
        return Provider.Property<T,double>(FrameworkElement.ActualHeightProperty, FrameworkElement.HeightProperty).Bl(); //.Restrict(0, double.MaxValue);
      }
      set { Height.Bind = value.Max(0); }
    }
    /// <summary>
    /// Gets or sets the UI element's right position. The right position is defined as Left + Width.
    /// </summary>
    public DoubleBl Right {
      get { return Left + Width; }
      set { Right.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's bottom position. The right position is defined as Top + Height.
    /// </summary>
    public DoubleBl Bottom {
      get { return Top + Height; }
      set { Bottom.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's size, defined as a point of its width and height.
    /// </summary>
    public Double2Bl Size {
      get { return new Double2Bl(Width, Height); }
      set { Size.Bind = value.Max(0d); }
    }

    public Double4Bl Bounds {
      get { return new Double4Bl(LeftTop, Size); }
      set { Bounds.Bind = value; }
    }

    /// <summary>
    /// Get or set the UI element's center relative point, which is Size / 2.
    /// </summary>
    public Double2Bl CenterSize
    {
      get { return new Double2Bl(Width / 2, Height / 2); }
      set { CenterSize.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's position with respect to its left-top corner.
    /// </summary>
    public Double2Bl LeftTop
    {
      get { return new Double2Bl(Left, Top); }
      set { LeftTop.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's position with respect to its right-bottom corner.
    /// </summary>
    public Double2Bl RightBottom
    {
      get { return new Double2Bl(Right, Bottom); }
      set { RightBottom.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's position with respect to its right-top corner.
    /// </summary>
    public Double2Bl RightTop {
      get { return new Double2Bl(Right, Top); }
      set { RightTop.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's position with respect to its left-bottom corner.
    /// </summary>
    public Double2Bl LeftBottom {
      get { return new Double2Bl(Left, Bottom); }
      set { LeftBottom.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's position with respect to its right-top corner.
    /// </summary>
    public Double2Bl CenterPosition {
      get { return new Double2Bl(Left + Width / 2, Top + Height / 2); }
      set { CenterPosition.Bind = value; }
    }

    private TransformBl RenderTransform0;
    /// <summary>
    ///     Gets or sets transform information that affects the rendering position of
    ///     this element. This is a dependency property. Will cache specified center size.
    /// </summary>
    public TransformBl RenderTransform {
      get {
        if (((object) RenderTransform0) == null)
          RenderTransform0 = new TransformBl(Provider.Property<T,Transform>(FrameworkElement.RenderTransformProperty)) {
            Origin = CenterSize,
          };
        return RenderTransform0;
      }
      set { RenderTransform.Bind = value; }
    }
    /// <summary>
    /// Directly set rotation of this element rather than go through a RenderTransform. Only use when direct access to property is needed.
    /// </summary>
    public DegreeBl AtRotation {
      get {
        return Provider.Property<T,double>(FrameworkElementBl.CenterRotationProperty.Property).Bl().Degrees();
      }
      set { AtRotation.Bind = value; }
    }
    public Double2Bl EnableAtRotation {
      set {
        RenderTransform[value].Rotate.Bind = AtRotation;
      }
    }
    /// <summary>
    /// Directly set scale of this element rather than go through a RenderTransform. Only use when direct access to property is needed.
    /// </summary>
    public Double2Bl AtScale {
      get {
        return Provider.Property<T,Point>(FrameworkElementBl.CenterScaleProperty.Property).Bl();
      }
      set { AtScale.Bind = value; }
    }
    public Double2Bl EnableAtScale {
      set {
        RenderTransform[value].Scale.Bind = AtScale;
      }
    }



    /// <summary>
    /// Translates a pixel-based peer position of a UI element into a percentage-based relative position of the UI element. 
    /// </summary>
    /// <param name="p">A pixel-based position relative to this UI element's container.</param>
    /// <returns>A percentage-based position relative to this UI element's position and size.</returns>
    public Double2Bl Relative(Double2Bl p) {
      return (p - LeftTop) / Size;
    }


    /// <summary>
    /// Gets or sets the UI element's position with respect to its center at the top
    /// </summary>
    public Double2Bl CenterTop {
      get { return new Double2Bl(Left + Width / 2, Top); }
      set { CenterTop.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's position with respect to its center at the bottom
    /// </summary>
    public Double2Bl CenterBottom {
      get { return new Double2Bl(Left + Width / 2, Bottom); }
      set { CenterBottom.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's position with respect to its center at the left
    /// </summary>
    public Double2Bl LeftCenter {
      get { return new Double2Bl(Left, Top + Height / 2); }
      set { LeftCenter.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's position with respect to its center at the right
    /// </summary>
    public Double2Bl RightCenter {
      get { return new Double2Bl(Right, Top + Height / 2); }
      set { RightCenter.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the UI element's Zindex to describe the order in Zbuffer
    /// </summary>
    public IntBl ZIndex {
      get { return Provider.Property<T,int>(Panel.ZIndexProperty).Bl(); }
      set { ZIndex.Bind = value; }
    }
    /// <summary>
    /// make two thumb,the red one is at the lefttop to drag, the blue one is at the rightbottom to scale
    /// </summary>
    public virtual bool HasThumbs {
      set {
        if (value) {
          new ThumbBl(PanelParent) {
            Background = Brushes.Red,
            MapF = (self,p) => p.Clamp(new Point(0, 0), PanelParent.Size),
            DragPoint = LeftTop, ZIndex = ZIndex + 1
          };
          new ThumbBl(PanelParent) {
            Background = Brushes.Blue,
            MapF = (self,p) => p.Clamp(new Point(0, 0), PanelParent.Size),
            DragPoint = Size + LeftTop, 
            ZIndex = ZIndex + 1
          };
        }
      }
    }
    /// <summary>
    /// make a thumb to rotate
    /// </summary>
    public virtual bool HasRotateThumb {
      set {
        if (value) {
          var r = RenderTransform.Rotate;
          new ThumbBl(PanelParent) {
            Background = Brushes.Purple,
            ZIndex = ZIndex + 1,
            DragPoint = r.Radians.SinCos * Width.Max(Height) + CenterPosition
          };
        }
      }
    }
    /// <summary>
    /// The pixel shader effect of this UI element.  Set this if you want to use a built-in pixel shader effect, otherwise use Effect.Custom to specify your own effect.
    /// </summary>
    public EffectBl Effect {
      get { return Provider.Property<T,Effect>(UIElement.EffectProperty); }
      set { this.Effect.Bind = value; }
    }
    /// <summary>
    /// Return a drag adapter that can be installed by calling Install. 
    /// </summary>
    public DragAdapter Drag {
      get {
        object value = Provider.Property<T,object>(FrameworkElementBl.DragAdapterProperty.Property).CurrentValue;
        if (value == null) {
          value = new DragAdapter(this);
          new ObjectBl(Provider.Property<T,object>(FrameworkElementBl.DragAdapterProperty.Property)).Now = (ObjectBl) value;
        }
        return (DragAdapter) value;
      }
    }

    /// <summary>
    /// Wrap thumb-like drag functionality.
    /// </summary>
    public class DragAdapter : DependencyObject {
      public class Driver {
        public Func<Func<BRAND, bool>> DetectStartDrag { set; private get; }
        public Action<Func<BRAND, bool>> DetectStopDrag { set; private get; }
        public Action<Func<BRAND, bool>> DetectMoveDrag { set; private get; }

      }
      private readonly BRAND Underlying;
      private static readonly GetProperty<DragAdapter, bool> IsDraggingProperty = "IsDragging".NewProperty<DragAdapter, bool>();

      /// <summary>
      /// Compute point property that drag delta is added to. By default, this is the LeftTop property of the framework element. Will be ignored if OnDrag is set.
      /// </summary>
      public Func<BRAND, Double2Bl> DragTarget { private get; set; }
      /// <summary>
      /// Manually deal with the drag delta, the argument of the action is the start drag point with respect to this UI element
      /// and the position of the mouse with respect to this UI element.
      /// By default, this is null and not used, if set this will be called rather than use DragTarget. 
      /// </summary>
      public Action<BRAND, Double2Bl, Double2Bl> OnDrag { private get; set; }

      /// <summary>
      /// Manually deal with the drag delta, the argument of the action is the start drag point with respect to this UI element 
      /// and the position of the mouse with respect to the containing canvas.
      /// By default, this is null and not used, if set this will be called rather than use OnDrag or DragTarget. 
      /// </summary>
      public Action<BRAND, Double2Bl, Double2Bl> OnDragInCanvas { private get; set; }

      /// <summary>
      /// Called when dragging starts with the point of contact relative to this UI element. 
      /// </summary>
      public Action<BRAND, Double2Bl> DragStart { private get; set; }
      /// <summary>
      /// Called when dragging stops with the point of contact relative to this UI element. 
      /// </summary>
      public Action<BRAND, Double2Bl> DragStop { private get; set; }
      /// <summary>
      /// Whether or not the element is being dragged. This is a dependency property. 
      /// </summary>
      public BoolBl IsDragging { get { return IsDraggingProperty[this]; }  }

      /// <summary>
      /// Whether to start dragging on a mouse down event. Default is to accept dragging. 
      /// </summary>
      public Func<BRAND, MouseButtonEventArgs, bool> DragAccept = (element, args) => true;


      /// <summary>
      /// Start dragging the element, this can be issued programmatically or automatically via MouseInstall and a MouseDown event.
      /// </summary>
      /// <param name="GetPosition">Function for getting input point of drag relative to a UI element. If null, will be the mouse position.</param>
      /// <param name="InstallMove">Function for installing move handlers, if null will install on mouse move.</param>
      /// <param name="DoCapture">Function for capturing input focus. If null will capture mouse.</param>
      public void StartDrag(Func<FrameworkElementBl,Double2Bl> GetPosition, Action<BRAND, Func<BRAND,bool>> InstallMove, Action<BRAND> DoCapture) {
        var element = Underlying;
        if (active) throw new NotSupportedException();
        if (GetPosition == null) GetPosition = element0 => element0.Mouse.Position;
        if (InstallMove == null) InstallMove = (element0, F) => element0.OnMouseMove = (element1, args) => F(element1);
        if (DoCapture == null) DoCapture = (element0) => System.Windows.Input.Mouse.Capture(element0.CurrentValue, CaptureMode.Element);
        active = true;

        IsDraggingProperty[this].Bl().Now = true;
        DoCapture(element);
        Double2Bl Begin = GetPosition(element).Now;
        Double2Bl ActualBegin = Begin.Now;
        DragStart(element, GetPosition(Underlying));
        (OnDrag == null || OnDragInCanvas == null).Assert();
        if (OnDragInCanvas != null) {
          InstallMove(element, element0 => {
            if (!active) return false;
            OnDragInCanvas(element0, Begin, GetPosition(element0.PanelParent));
            return true;
          });
        } else if (OnDrag != null) {
          InstallMove(element, element0 => {
            if (!active) return false;
            OnDrag(element0, Begin, GetPosition(element0));
            return true;
          });
        } else if (DragTarget != null) {
          InstallMove(element, element0 => {
            if (!active) return false;
            DragTarget(element0).Now += (GetPosition(element0) - Begin);
            return true;
          });
        }
      }
      /// <summary>
      /// Stop dragging, can be called programmatically or automatically on MouseUp via MouseInstall.
      /// </summary>
      /// <param name="DoUncapture">Uncapture input focus. If null will uncapture mouse focus.</param>
      public void StopDrag(Action<BRAND> DoUncapture) {
        var element = Underlying;
        if (DoUncapture == null) 
          DoUncapture = element1 => System.Windows.Input.Mouse.Capture(element1.CurrentValue, CaptureMode.None);
        if (!active) throw new NotSupportedException();
        active = false;
        DragStop(element, element.Mouse.Position);
        DoUncapture(element);
        IsDraggingProperty[this].Bl().Now = false;
      }

      private bool active = false;
      private bool mouseInstalled = false;
      /// <summary>
      /// If true, install this drag adapter using the configuration specified according to this Bling value. Note that after the drag adapter is installed, it should no longer be manipulated
      /// except to uninstall. 
      /// </summary>
      public bool MouseInstall {
        set {
          if (!value) {
            mouseInstalled = false; return;
          }
          active = false;
          mouseInstalled = true;
          Underlying.OnMouseDown = (element, downArgs) => {
            if (!DragAccept(element,downArgs)) return false;
            if (!mouseInstalled) return false;
            StartDrag(null, null, null);
            element.OnMouseUp = (element0, upArgs) => {
              if (active)
                StopDrag(null);
              return false;
            };
            return true;
          };
        }
      }
      internal DragAdapter(BRAND Underlying) {
        this.Underlying = Underlying;
        DragTarget = (element) => element.LeftTop;
        DragStart = (element, delta) => { };
        DragStop = (element, delta) => { };

      }
    }
  }


  /// <summary>
  /// Bl wrapper around FontFamily
  /// </summary>
  public partial class FontFamilyBl : Brand<FontFamily, FontFamilyBl> {
    public FontFamilyBl(Expr<FontFamily> v) : base(v) { }
    public FontFamilyBl() : base(new FontFamily()) { }
    public static implicit operator FontFamilyBl(Expr<FontFamily> v) { return new FontFamilyBl(v); }
    public static implicit operator FontFamilyBl(FontFamily v) { return new Constant<FontFamily>(v); }

    public static implicit operator FontFamilyBl(string v) { return v.Convert<FontFamily>(); }

    static FontFamilyBl() {
    }
  }
  /// <summary>
  /// Bl wrapper around FontStyle
  /// </summary>
  public partial class FontStyleBl : Brand<FontStyle, FontStyleBl> {
    public FontStyleBl(Expr<FontStyle> v) : base(v) { }
    public FontStyleBl() : base(new FontStyle()) { }
    public static implicit operator FontStyleBl(Expr<FontStyle> v) { return new FontStyleBl(v); }
    public static implicit operator FontStyleBl(FontStyle v) { return new Constant<FontStyle>(v); }

    static FontStyleBl() {
    }
  }

  /*
  public partial class TextAlignmentBl : BrandedBlValue<TextAlignment, TextAlignmentBl> {
    public TextAlignmentBl(Value<TextAlignment> v) : base(v) { }
    public static implicit operator TextAlignmentBl(Value<TextAlignment> v) { return new TextAlignmentBl(v); }
    public static implicit operator TextAlignmentBl(TextAlignment v) { return new Constant<TextAlignment>(v); }

    static TextAlignmentBl() {
      Register(v => v);
    }
  }*/

  /// <summary>
  /// Bl wrapper around FontWeight
  /// </summary>
  public partial class FontWeightBl : Brand<FontWeight, FontWeightBl> {
    public FontWeightBl(Expr<FontWeight> v) : base(v) { }
    public FontWeightBl() : base(new FontWeight()) { }
    public static implicit operator FontWeightBl(Expr<FontWeight> v) { return new FontWeightBl(v); }
    public static implicit operator FontWeightBl(FontWeight v) { return new Constant<FontWeight>(v); }

    /// <summary>
    /// Sets if the font is in bold type
    /// </summary>
    public bool IsBold {
      set { if (value) this.Bind = FontWeights.Bold; }
    }
    /// <summary>
    /// Sets if the font is in black type
    /// </summary>
    public bool IsBlack {
      set { if (value) this.Bind = FontWeights.Black; }
    }
    static FontWeightBl() {
    }
  }
  public interface IFontBl {
    /// <summary>
    ///     Gets or sets the font size. This is a dependency property.
    /// </summary>
    /// <returns>
    ///    The size of the text in the System.Windows.Controls.Control. The default
    ///     is System.Windows.SystemFonts.MessageFontSize. The font size must be a positive
    ///     number.
    ///</returns>    
    DoubleBl Size { get; set; }
    /// <summary>
    ///     Gets or sets the font style. This is a dependency property.
    /// </summary>
    /// <returns>
    ///     A System.Windows.FontStyle value. The default is System.Windows.FontStyles.Normal.
    ///</returns>    
    FontStyleBl Style { get; set; }
    /// <summary>
    ///     Gets or sets the weight or thickness of the specified font. This is a dependency
    ///    property.
    /// </summary>
    /// <returns>
    ///     A System.Windows.FontWeight value. The default is System.Windows.FontWeights.Normal.
    ///</returns>    
    FontWeightBl Weight { get; set; }
    FontFamilyBl Family { get; set; }
    /// <summary>
    /// Foreground color of font.
    /// </summary>
    BrushBl Brush { get; set; }

    IFontBl Bind { set; }
    IFontBl Now { set; }
  }
  public abstract class BaseFontBl : IFontBl {
    /// <summary>
    ///     Gets or sets the font size. This is a dependency property.
    /// </summary>
    /// <returns>
    ///    The size of the text in the System.Windows.Controls.Control. The default
    ///     is System.Windows.SystemFonts.MessageFontSize. The font size must be a positive
    ///     number.
    ///</returns>    
    public abstract DoubleBl Size { get; set; }
    /// <summary>
    ///     Gets or sets the font style. This is a dependency property.
    /// </summary>
    /// <returns>
    ///     A System.Windows.FontStyle value. The default is System.Windows.FontStyles.Normal.
    ///</returns>    
    public abstract FontStyleBl Style { get; set; }
    /// <summary>
    ///     Gets or sets the weight or thickness of the specified font. This is a dependency
    ///    property.
    /// </summary>
    /// <returns>
    ///     A System.Windows.FontWeight value. The default is System.Windows.FontWeights.Normal.
    ///</returns>    
    public abstract FontWeightBl Weight { get; set; }
    public abstract FontFamilyBl Family { get; set; }
    /// <summary>
    /// Foreground color of font.
    /// </summary>
    public abstract BrushBl Brush { get; set; }
    public IFontBl Bind {
      set {
        if (value is FontCl) {
          if (((object)value.Brush) != null)
            this.Brush.Bind = value.Brush;
          if (((object)value.Family) != null)
            this.Family.Bind = value.Family;
          if (((object)value.Size) != null)
            this.Size.Bind = value.Size;
          if (((object)value.Style) != null)
            this.Style.Bind = value.Style;
          if (((object)value.Weight) != null)
            this.Weight.Bind = value.Weight;
        } else {
          this.Brush.Bind = value.Brush;
          this.Family.Bind = value.Family;
          this.Size.Bind = value.Size;
          this.Style.Bind = value.Style;
          this.Weight.Bind = value.Weight;
        }
      }
    }
    public IFontBl Now {
      set {
        if (value is FontCl) {
          if (((object)value.Family) != null)
            this.Family.Now = value.Family;
          if (((object)value.Size) != null)
            this.Size.Now = value.Size;
          if (((object)value.Style) != null)
            this.Style.Now = value.Style;
          if (((object)value.Weight) != null)
            this.Weight.Now = value.Weight;

        } else {
          this.Family.Now = value.Family;
          this.Size.Now = value.Size;
          this.Style.Now = value.Style;
          this.Weight.Now = value.Weight;
        }
      }
    }
  }

  public class FontCl : BaseFontBl {
    /// <summary>
    ///     Gets or sets the font size. This is NOT a dependency property.
    /// </summary>
    /// <returns>
    ///    The size of the text in the System.Windows.Controls.Control. The default
    ///     is System.Windows.SystemFonts.MessageFontSize. The font size must be a positive
    ///     number.
    ///</returns>    
    public override DoubleBl Size { get; set; }
    /// <summary>
    ///     Gets or sets the font style. This is NOT a dependency property.
    /// </summary>
    /// <returns>
    ///     A System.Windows.FontStyle value. The default is System.Windows.FontStyles.Normal.
    ///</returns>    
    public override FontStyleBl Style { get; set; }
    /// <summary>
    ///     Gets or sets the weight or thickness of the specified font. This is NOT a dependency
    ///    property.
    /// </summary>
    /// <returns>
    ///     A System.Windows.FontWeight value. The default is System.Windows.FontWeights.Normal.
    ///</returns>    
    public override FontWeightBl Weight { get; set; }
    public override FontFamilyBl Family { get; set; }
    /// <summary>
    /// Foreground color of font.
    /// </summary>
    public override BrushBl Brush { get; set; }
  }

  internal class FontBl<T> : BaseFontBl where T : FrameworkElement {
    internal Expr<T> Underlying;
    internal DependencyProperty SizeProperty;
    internal DependencyProperty StyleProperty;
    internal DependencyProperty WeightProperty;
    internal DependencyProperty FamilyProperty;
    internal DependencyProperty BrushProperty;

    internal FontBl() { }

    //public FrameworkElementBl Target { get { return Underlying; } }

    /// <summary>
    ///     Gets or sets the font size. This is a dependency property.
    /// </summary>
    /// <returns>
    ///    The size of the text in the System.Windows.Controls.Control. The default
    ///     is System.Windows.SystemFonts.MessageFontSize. The font size must be a positive
    ///     number.
    ///</returns>    
    public override DoubleBl Size { get { return Underlying.Property<T,double>(SizeProperty); } set { Size.Bind = value; } }
    /// <summary>
    ///     Gets or sets the font style. This is a dependency property.
    /// </summary>
    /// <returns>
    ///     A System.Windows.FontStyle value. The default is System.Windows.FontStyles.Normal.
    ///</returns>    
    public override FontStyleBl Style { get { return Underlying.Property<T,FontStyle>(StyleProperty); } set { Style.Bind = value; } }
    /// <summary>
    ///     Gets or sets the weight or thickness of the specified font. This is a dependency
    ///    property.
    /// </summary>
    /// <returns>
    ///     A System.Windows.FontWeight value. The default is System.Windows.FontWeights.Normal.
    ///</returns>    
    public override FontWeightBl Weight { get { return Underlying.Property<T,FontWeight>(WeightProperty); } set { Weight.Bind = value; } }

    public override FontFamilyBl Family { get { return Underlying.Property<T,FontFamily>(FamilyProperty); } set { Family.Bind = value; } }


    /// <summary>
    /// Foreground color of font.
    /// </summary>
    public override BrushBl Brush { get { return Underlying.Property<T,Brush>(BrushProperty); } set { Brush.Bind = value; } }
  }


  /// <summary>
  ///  Represents the base class for user interface (UI) elements that use a System.Windows.Controls.ControlTemplate
  ///     to define their appearance.
  /// </summary>
  /// <typeparam name="TARGET"></typeparam>
  public abstract partial class ControlBl<T,SELF> : FrameworkElementBl<T,SELF> where T : Control where SELF : ControlBl<T,SELF> {
    public ControlBl(Expr<T> Provider) : base(Provider) { }
    public ControlBl() : base() { }
    public ControlBl(PanelBl canvas, T target) : base(canvas, target) { }
    /// <summary>
    /// Access font properties.
    /// </summary>
    public IFontBl Font {
      get {
        return new FontBl<T>() {
          Underlying = (Provider),
          SizeProperty = Control.FontSizeProperty,
          WeightProperty = Control.FontWeightProperty,
          StyleProperty = Control.FontStyleProperty,
          BrushProperty = Control.ForegroundProperty,
          FamilyProperty = Control.FontFamilyProperty,
        };
      }
      set { Font.Bind = (value); }
    }
    /// <summary>
    ///     Gets or sets the alignment of the control's content. Default is Horizontal Left Vertical Top.
    /// </summary>
    public AlignmentSet ContentAlignment {
      get { return new AlignmentSet() { Underlying = Provider, HorizontalAlignmentProperty = Control.HorizontalContentAlignmentProperty, VerticalAlignmentProperty = Control.VerticalContentAlignmentProperty }; }
      set { ContentAlignment.Bind = (value); }
    }


    /// <summary>
    ///     Gets or sets a brush that describes the background of a control. This is
    ///     a  dependency property.
    /// </summary>
    /// <returns>
    ///     The brush that is used to fill the background of the control. The default
    ///     is System.Windows.Media.Brushes.Transparent.
    ///</returns> 
    public BrushBl Background {
      get { return Provider.Property<T, Brush>(Control.BackgroundProperty).Bl(); }
      set { Background.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a brush that describes the foreground color. This is a dependency
    ///     property.
    /// </summary>
    /// <returns>
    ///     The brush that paints the foreground of the control. The default value is
    ///     the system dialog font color.
    ///</returns>    
    public BrushBl Foreground {
      get { return Provider.Property<T, Brush>(Control.ForegroundProperty).Bl(); }
      set { Foreground.Bind = value; }
    }

    /// <summary>
    /// Get and set border properties.
    /// </summary>
    public BorderInfoSet Border {
      get {
        return new BorderInfo<T> {
          Underlying = Provider,
          BorderBrushProperty = Control.BorderBrushProperty,
          BorderThicknessProperty = Control.BorderThicknessProperty,
        };
      }
      set {
        Border.Bind(value);
      }
    }
    /// <summary>
    ///     The amount of space between the content of a System.Windows.Controls.Control
    ///     and its System.Windows.FrameworkElement.Margin or System.Windows.Controls.Border.
    ///     The default is a thickness of 0 on all four sides.
    /// </summary>
    public ThicknessBl Padding {
      get { return Provider.Property<T, Thickness>(Control.PaddingProperty); }
      set {
        var d = Provider.Property<T, Thickness>(Control.PaddingProperty).ToBling().Bl();
        d.Bind = value.All;
      }
    }
  }
  public abstract partial class RangeBaseBl<T,SELF> : ControlBl<T,SELF> where T : RangeBase where SELF : RangeBaseBl<T,SELF> {
    public RangeBaseBl(Expr<T> Provider) : base(Provider) { }
    public RangeBaseBl(PanelBl canvas, T target) : base(canvas, target) {}
    public static implicit operator DoubleBl(RangeBaseBl<T, SELF> v) { return v.Value; }

    /// <summary>
    ///     Gets or sets the current magnitude of the range control. This is a dependency property. Returns
    ///    the current magnitude of the range control. The default is 0.
    ///</summary>    
    public DoubleBl Value {
      get { return Provider.Property<T, double>(RangeBase.ValueProperty).Bl(); }
      set { Value.Bind = value; }
    }
    /// <summary>
    ///    Gets or sets the highest possible System.Windows.Controls.Primitives.RangeBase.Value
    ///     of the range element. This is a dependency property. Returns 
    ///     the highest possible System.Windows.Controls.Primitives.RangeBase.Value of
    ///     the range element. The default is 1.
    ///</summary>    
    public DoubleBl Maximum {
      get { return Provider.Property<T, double>(RangeBase.MaximumProperty).Bl(); }
      set { Maximum.Bind = value; }
    }
    /// <summary>
    ///    Gets or sets the System.Windows.Controls.Primitives.RangeBase.Minimum possible
    ///     System.Windows.Controls.Primitives.RangeBase.Value of the range element.
    ///     This is a dependency property. Returns 
    ///     System.Windows.Controls.Primitives.RangeBase.Minimum possible System.Windows.Controls.Primitives.RangeBase.Value
    ///     of the range element. The default is 0.
    /// </summary>
    public DoubleBl Minimum {
      get { return Provider.Property<T, double>(RangeBase.MinimumProperty).Bl(); }
      set { Minimum.Bind = value; }
    }
    private class RangeSetX : RangeBl<DoubleBl, DoubleBl> {
      internal SELF Self;
      public override DoubleBl Maximum {
        get { return Self.Maximum; }
        set { Maximum.Bind = value;  }
      }
      public override DoubleBl Minimum {
        get { return Self.Minimum; }
        set { Minimum.Bind = value; }
      }
    }
    public RangeBl<DoubleBl, DoubleBl> Range { get { return new RangeSetX() { Self = this }; } set { Range.Bind(value); } }

    public class ChangeSet {
      internal Expr<T> Underlying;
      /// <summary>
      ///    Gets or sets a System.Windows.Controls.Primitives.RangeBase.Value to be added
      ///     to or subtracted from the System.Windows.Controls.Primitives.RangeBase.Value
      ///     of a System.Windows.Controls.Primitives.RangeBase control. This is a dependency
      ///     property.
      /// </summary>
      /// <returns>
      ///    System.Windows.Controls.Primitives.RangeBase.Value to add to or subtract
      ///     from the System.Windows.Controls.Primitives.RangeBase.Value of the System.Windows.Controls.Primitives.RangeBase
      ///     element. The default is 0.1.
      ///</returns>    
      public DoubleBl Small {
        get { return Underlying.Property<T, double>(RangeBase.SmallChangeProperty).Bl(); }
        set { Small.Bind = value; }
      }
      /// <summary>
      ///    Gets or sets a value to be added to or subtracted from the System.Windows.Controls.Primitives.RangeBase.Value
      ///     of a System.Windows.Controls.Primitives.RangeBase control. This is a dependency
      ///     property.
      /// </summary>
      /// <returns>
      ///    System.Windows.Controls.Primitives.RangeBase.Value to add to or subtract
      ///     from the System.Windows.Controls.Primitives.RangeBase.Value of the System.Windows.Controls.Primitives.RangeBase
      ///     element. The default is 1.
      ///</returns>    
      public DoubleBl Large {
        get { return Underlying.Property<T, double>(RangeBase.LargeChangeProperty).Bl(); }
        set { Large.Bind = value; }
      }
      internal ChangeSet Bind {
        set {
          this.Small = value.Small;
          this.Large = value.Large;
        }
      }
    }
    /// <summary>
    /// Large and small change values. 
    /// </summary>
    public ChangeSet Change {
      get { return new ChangeSet() { Underlying = Provider }; }
      set { Change.Bind = value; }
    }
    public Action<SELF, double, double> ValueChanged {
      set {
        CurrentValue.ValueChanged += (x, y) => {
          value(ToBrand(new Constant<T>((T)x)), y.OldValue, y.NewValue);
        };
      }
    }
  }
  public abstract partial class TextBoxBl<T, BRAND> : ControlBl<T, BRAND>
    where T : TextBoxBase
    where BRAND : TextBoxBl<T, BRAND> {
    public TextBoxBl(Expr<T> Provider) : base(Provider) { }
    public TextBoxBl(PanelBl canvas, T target) : base(canvas, target) { }
    /// <summary>
    ///     Gets or sets a value that indicates how the text editing control responds
    ///     when the user presses the ENTER key.
    /// </summary>
    /// <remarks>
    ///     true if pressing the ENTER key inserts a new line at the current cursor position;
    ///     otherwise, the ENTER key is ignored. The default value is false for System.Windows.Controls.TextBox
    ///     and true for System.Windows.Controls.RichTextBox.
    ///     </remarks>
    public BoolBl AcceptsReturn { get { return Provider.Property<T,bool>(TextBoxBase.AcceptsReturnProperty); } set { AcceptsReturn.Bind = value; } }
    /// <summary>
    ///     Gets or sets a value that indicates how the text editing control responds
    ///     when the user presses the TAB key. This is a dependency property.
    ///</summary>
    /// <remarks>
    ///     true if pressing the TAB key inserts a tab character at the current cursor
    ///     position; false if pressing the TAB key moves the focus to the next control
    ///     that is marked as a tab stop and does not insert a tab character.  The default
    ///     value is false.
    ///     </remarks>
    public BoolBl AcceptsTab { get { return Provider.Property<T,bool>(TextBoxBase.AcceptsTabProperty); } set { AcceptsTab.Bind = value; } }
    /// <summary>
    ///     Gets or sets a value that determines whether when a user selects part of
    ///     a word by dragging across it with the mouse, the rest of the word is selected.
    ///     This is a dependency property.
    ///</summary>
    /// <remarks>
    ///     true if automatic word selection is enabled; otherwise, false.  The default
    ///     value is false.
    ///     </remarks>
    public BoolBl AutoWordSelection { get { return Provider.Property<T,bool>(TextBoxBase.AutoWordSelectionProperty); } set { AutoWordSelection.Bind = value; } }
    /// <summary>
    ///     Gets or sets a value that indicates whether the text editing control is read-only
    ///     to a user interacting with the control. This is a dependency property.
    ///</summary>
    /// <remarks>
    ///     true if the contents of the text editing control are read-only to a user;
    ///     otherwise, the contents of the text editing control can be modified by the
    ///     user. The default value is false.
    ///     </remarks>
    public BoolBl IsReadOnly { get { return Provider.Property<T,bool>(TextBoxBase.IsReadOnlyProperty); } set { IsReadOnly.Bind = value; } }
    /// <summary>
    ///     Gets or sets a value that indicates whether undo support is enabled for the
    ///     text-editing control. This is a dependency property.
    ///</summary>
    /// <remarks>
    ///     true to enable undo support; otherwise, false. The default value is true.
    ///     </remarks>
    public BoolBl IsUndoEnabled { get { return Provider.Property<T,bool>(TextBoxBase.IsUndoEnabledProperty); } set { IsUndoEnabled.Bind = value; } }
    /// <summary>
    ///     Gets or sets a value that indicates whether a vertical scroll bar is shown.
    ///     This is a dependency property.
    ///</summary>
    /// <remarks>
    ///     A value that is defined by the System.Windows.Controls.ScrollBarVisibility
    ///     enumeration. The default value is System.Windows.Visibility.Hidden.
    ///     </remarks>
    public EnumBl<ScrollBarVisibility> VerticalScrollBarVisibility { get { return Provider.Property<T, ScrollBarVisibility>(TextBoxBase.VerticalScrollBarVisibilityProperty); } set { VerticalScrollBarVisibility.Bind = value; } }
    /// <summary>
    //     Gets or sets a value that indicates whether a horizontal scroll bar is shown.
    //     This is a dependency property.
    ///</summary>
    /// <remarks>
    //     A value that is defined by the System.Windows.Controls.ScrollBarVisibility
    //     enumeration.The default value is System.Windows.Visibility.Hidden.
    ///     </remarks>
    public EnumBl<ScrollBarVisibility> HorizontalScrollBarVisibility { get { return Provider.Property<T, ScrollBarVisibility>(TextBoxBase.HorizontalScrollBarVisibilityProperty); } set { VerticalScrollBarVisibility.Bind = value; } }
    /// <summary>
    ///     Gets or sets the number of actions stored in the undo queue.
    ///</summary>
    /// <remarks>
    ///     The number of actions stored in the undo queue. The default is –1, which
    ///     means the undo queue is limited to the memory that is available.
    ///     </remarks>
    /// <exception cref="System.InvalidOperationException">
    ///     System.Windows.Controls.Primitives.TextBoxBase.UndoLimit is set after calling
    ///     System.Windows.Controls.Primitives.TextBoxBase.BeginChange() and before calling
    ///     System.Windows.Controls.Primitives.TextBoxBase.EndChange().
    /// </exception>
    public IntBl UndoLimit { get { return Provider.Property<T,int>(TextBoxBase.UndoLimitProperty); } set { UndoLimit.Bind = value; } }

    /// <summary>
    ///     Selects the entire contents of the text editing control.
    /// </summary>
    public Command SelectAll {
      get {
        var lblF = AsFunc;
        return new Command("SelectAll", () => lblF().SelectAll());
      }
    }
    public Action<BRAND> TextChanged {
      set { CurrentValue.TextChanged += (x, y) => value(ToBrand(new Constant<T>((T)x))); }
    }

  }
  /// <summary>
  /// Represents a control that can be used to display or edit unformatted text.
  /// </summary>
  public partial class TextBoxBl : TextBoxBl<TextBox, TextBoxBl> {
    public TextBoxBl() : base(new Constant<TextBox>(new TextBox())) { }
    public TextBoxBl(Expr<TextBox> Provider) : base(Provider) { }
    public TextBoxBl(PanelBl canvas) : base(canvas, new TextBox()) {
    }
    public static implicit operator TextBoxBl(Expr<TextBox> target) { return new TextBoxBl((target)); }
    public static implicit operator TextBoxBl(TextBox target) { return (new Constant<TextBox>(target)); }


    /// <summary>
    ///     Gets or sets the text contents of the text box. This is a dependency property.
    ///</summary><remarks>
    ///     A string containing the text contents of the text box. The default is an
    ///     empty string ("").
    ///     </remarks>
    public StringBl Text {
      get { return Provider.Property<TextBox, string>(TextBox.TextProperty); }
      set { Text.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the maximum number of characters that can be manually entered
    ///     into the text box. This is a dependency property.
    ///</summary><remarks>
    ///     The maximum number of characters that can be manually entered into the text
    ///     box. The default is 0, which indicates no limit.
    ///     </remarks>
    public IntBl MaxLength { get { return Provider.Property<TextBox, int>(TextBox.MaxLengthProperty); } set { MaxLength.Bind = value; } }
    /// <summary>
    ///     Gets or sets the maximum number of visible lines. This is a dependency property.
    ///</summary><remarks>
    ///     The maximum number of visible lines. The default is System.Int32.MaxValue.
    ///     </remarks>
    /// <exception cref="System.Exception">
    ///     System.Windows.Controls.TextBox.MaxLines is less than System.Windows.Controls.TextBox.MinLines.
    /// </exception>
    public IntBl MaxLines { get { return Provider.Property<TextBox, int>(TextBox.MaxLinesProperty); } set { MaxLines.Bind = value; } }
    /// <summary>
    ///     Gets or sets the minimum number of visible lines. This is a dependency property.
    ///</summary><remarks>
    ///     The minimum number of visible lines. The default is 1.
    ///     </remarks>
    /// <exception cref="System.Exception">
    ///     System.Windows.Controls.TextBox.MinLines is greater than System.Windows.Controls.TextBox.MaxLines.
    /// </exception>
    public IntBl MinLines { get { return Provider.Property<TextBox,int>(TextBox.MinLinesProperty); } set { MinLines.Bind = value; } }

    public EnumBl<TextWrapping> TextWrapping {
      get { return Provider.Property<TextBox, TextWrapping>(TextBox.TextWrappingProperty); }
      set { TextWrapping.Bind = value; }
    }
  }
  /// <summary>
  /// Represents a control that lets the user select from a range of values by
  ///     moving a System.Windows.Controls.Primitives.Track.Thumb control along a System.Windows.Controls.Primitives.Track.
  /// </summary>
  public partial class SliderBl : RangeBaseBl<Slider,SliderBl> {
    public SliderBl() : base(new Constant<Slider>(new Slider())) { }
    public SliderBl(Expr<Slider> Provider) : base(Provider) { }
    public SliderBl(PanelBl canvas) : base(canvas, new Slider()) {
      this.ToolTip = this.Value.ToStringBl();
      this.Minimum = 0d;
      this.Maximum = 1d;
      this.Value = 0d;
    }
    public static implicit operator SliderBl(Expr<Slider> target) { return new SliderBl((target)); }
    public static implicit operator SliderBl(Slider target) { return (new Constant<Slider>(target)); }
    /// <summary>
    ///    Gets or sets the orientation of a System.Windows.Controls.Slider. This is
    ///     a dependency property.
    /// </summary>
    /// <returns>
    ///    One of the System.Windows.Controls.Slider.Orientation values. The default
    ///     is System.Windows.Controls.Orientation.Horizontal.
    ///</returns>    
    public OrientationBl Orientation {
      get { return Provider.Property<Slider,Orientation>(Slider.OrientationProperty); }
      set { Orientation.Bind = value; }
    }
  }





  /// <summary>
  /// Represents a control that provides a scroll bar that has a sliding System.Windows.Controls.Primitives.Thumb
  ///     whose position corresponds to a value.
  /// </summary>
  public class ScrollBarBl : RangeBaseBl<ScrollBar, ScrollBarBl> {
    public ScrollBarBl(Expr<ScrollBar> Provider) : base(Provider) { }
    public ScrollBarBl(PanelBl canvas) : base(canvas, new ScrollBar()) { }
    public ScrollBarBl() : base(new Constant<ScrollBar>(new ScrollBar())) { }
    /// <summary>
    /// Gets or sets the amount of the scrollable content that is currently visible.
    /// </summary>
    public DoubleBl ViewportSize {
      get {
        return Provider.Property<ScrollBar,double>(ScrollBar.ViewportSizeProperty);
      }
      set {
        ViewportSize.Bind = value;
      }
    }
    /// <summary>
    /// Gets or sets whether the System.Windows.Controls.Primitives.ScrollBar is
    ///     displayed horizontally or vertically. This is a dependency property.
    /// </summary>
    public OrientationBl Orientation {
      get {
        return Provider.Property<ScrollBar,Orientation>(ScrollBar.OrientationProperty);
      }
      set {
        Orientation.Bind = value;
      }
    }
  }
  public abstract partial class DecoratorBl<T, SELF> : FrameworkElementBl<T, SELF>
    where T : Decorator
    where SELF : DecoratorBl<T, SELF> {
    public DecoratorBl(Expr<T> Provider) : base(Provider) { }
    public DecoratorBl(PanelBl canvas, T target)
      : base(canvas, target) {
    }
    public UIElementBl Child {
      get { return Provider.Map<UIElement>(t => t.Child); }
      set { CurrentValue.Child = value.CurrentValue; }
    }
  }
  public class TextBlockBl : FrameworkElementBl<TextBlock, TextBlockBl> {
    public TextBlockBl(Expr<TextBlock> Provider) : base(Provider) { }
    public TextBlockBl(PanelBl canvas) : base(canvas, new TextBlock()) { }
    public TextBlockBl() : base(new TextBlock()) { }
    public static implicit operator TextBlockBl(Expr<TextBlock> v) { return new TextBlockBl(v); }
    static TextBlockBl() {
    }
    public StringBl Text {
      get { return Provider.Property<TextBlock, string>(TextBlock.TextProperty); }
      set { Text.Bind = value; }
    }
    /// <summary>
    /// Get or set font properties.
    /// </summary>
    public IFontBl Font {
      get {
        return new FontBl<TextBlock>() {
          Underlying = (Provider),
          SizeProperty = TextBlock.FontSizeProperty,
          WeightProperty = TextBlock.FontWeightProperty,
          StyleProperty = TextBlock.FontStyleProperty,
          BrushProperty = TextBlock.ForegroundProperty,
          FamilyProperty = TextBlock.FontFamilyProperty,
        };
      }
      set {
        Font.Bind= (value);
      }
    }
    public EnumBl<TextAlignment> TextAlignment {
      get { return Provider.Property<TextBlock, TextAlignment>(TextBlock.TextAlignmentProperty); }
      set { TextAlignment.Bind = value; }
    }
    public EnumBl<TextWrapping> TextWrapping {
      get { return Provider.Property<TextBlock, TextWrapping>(TextBlock.TextWrappingProperty); }
      set { TextWrapping.Bind = value; }
    }
    public BrushBl Foreground {
      get { return Provider.Property<TextBlock, Brush>(TextBlock.ForegroundProperty); }
      set { Foreground.Bind = value; }
    }
    public BrushBl Background {
      get { return Provider.Property<TextBlock,Brush>(TextBlock.BackgroundProperty); }
      set { Background.Bind = value; }
    }
    /// <summary>
    ///     The amount of space between the content of a System.Windows.Controls.Control
    ///     and its System.Windows.FrameworkElement.Margin or System.Windows.Controls.Border.
    ///     The default is a thickness of 0 on all four sides.
    /// </summary>
    public ThicknessBl Padding {
      get { return Provider.Property<TextBlock, Thickness>(TextBlock.PaddingProperty); }
      set {
        var d = Provider.Property<TextBlock, Thickness>(TextBlock.PaddingProperty).ToBling().Bl();
        d.Bind = value.All;
      }
    }

  }

  public abstract class BorderInfoSet {
    /// <summary>
    /// Gets or sets the System.Windows.Media.Brush that draws the outer border color.
    /// </summary>
    public abstract BrushBl Brush { get; set; }
    /// <summary>
    /// Gets or sets the relative System.Windows.Thickness of a System.Windows.Controls.Border.
    /// </summary>
    public abstract ThicknessBl Thickness { get; set; }
    public void Bind(BorderInfoSet info) {
      this.Brush = info.Brush; this.Thickness = info.Thickness;
    }
  }  
  internal class BorderInfo<T> : BorderInfoSet where T : FrameworkElement {    
    internal DependencyProperty BorderBrushProperty { private get; set; }    
    internal DependencyProperty BorderThicknessProperty { private get; set; }    
    internal Expr<T> Underlying { private get; set; }    
    public override BrushBl Brush {     
      get { return Underlying.Property<T,Brush>(BorderBrushProperty); }      
      set { Brush.Bind = value; }    }
    public override ThicknessBl Thickness {      
      get { return Underlying.Property<T,Thickness>(BorderThicknessProperty); }      
      set {
        Underlying.Property<T,Thickness>(BorderThicknessProperty).ToBling().Bl().Bind = value.All;
      }
    }  
  }
  /*
  class CornerRadiusArity : Vecs.Arity4<double, CornerRadius, CornerRadiusArity> {
    public override CornerRadius Make(params double[] Params) {
      return new CornerRadius(Params[0], Params[1], Params[2], Params[3]);
    }
    public override double Access(CornerRadius Value, int Idx) {
      switch (Idx) {
        case 0: return Value.TopLeft;
        case 1: return Value.TopRight;
        case 2: return Value.BottomRight;
        case 3: return Value.BottomLeft;
        default: throw new NotSupportedException();
      }
    }
    public override string[] PropertyNames {
      get {
        return new string[] {
        "TopLeft",
        "TopRight",
        "BottomRight",
        "BottomLeft",
      };
      }
    }
    internal static void CheckInit() { Extensions.Trace(ArityI + " " + typeof(CornerRadiusArity)); }
  }
  */

  public abstract class BorderBl<T, BRAND> : DecoratorBl<T, BRAND>, IExtends<BRAND,BorderBl>
    where T : Border
    where BRAND : BorderBl<T, BRAND> {
    public BorderBl(Expr<T> Provider) : base(Provider) { }
    public BorderBl(PanelBl canvas, T t) : base(canvas, t) { }
    public static implicit operator BorderBl(BorderBl<T, BRAND> canvas) {
      return BorderBl.UpCast(canvas);
    }
  }
  /// <summary>
  /// Represents the radii of a rectangle's corners.
  /// </summary>
  public class CornerRadiusBl  {
    public CornerRadiusBl() {
      BottomLeft = 0;
      BottomRight = 0;
      TopLeft = 0;
      TopRight = 0; 
    }
    public static implicit operator CornerRadiusBl(double d) {
      return d.Bl();
    }
    public static implicit operator CornerRadiusBl(DoubleBl d) {
      return new CornerRadiusBl() {
        BottomLeft = d,
        BottomRight = d,
        TopLeft = d,
        TopRight = d,
      };
    }

    public static explicit operator CornerRadiusBl(Double4Bl e) {
      return new CornerRadiusBl() {
        BottomLeft = e.X,
        BottomRight = e.Y,
        TopLeft = e.Z,
        TopRight = e.W,
      };
    }
    public static explicit operator Double4Bl(CornerRadiusBl v) {
      return new Double4Bl(v.BottomLeft, v.BottomRight, v.TopLeft, v.TopRight);
    }
    
    /// <summary>
    ///     Gets or sets the radius of the bottom-left corner. The default is 0.
    /// </summary>
    public DoubleBl BottomLeft { get; set; }
    /// <summary>
    ///     Gets or sets the radius of the bottom-right corner. The default is 0.
    /// </summary>
    public DoubleBl BottomRight { get; set; }
    /// <summary>
    ///     Gets or sets the radius of the top-left corner. The default is 0.
    /// </summary>
    public DoubleBl TopLeft { get; set; }
    /// <summary>
    ///     Gets or sets the radius of the top-right corner. The default is 0.
    /// </summary>
    public DoubleBl TopRight { get; set; }
  }
  /*
  public abstract class DecoratorBl<T, SELF> : FrameworkElementBl<T, SELF> where T : Decorator where SELF : DecoratorBl<T,SELF> {

  }*/

  public class BorderBl : BorderBl<Border, BorderBl> {
    public BorderBl(Expr<Border> Provider) : base(Provider) { }
    public BorderBl() : this(new Constant<Border>(new Border())) { }
    public BorderBl(PanelBl canvas) : base(canvas, new Border()) { }
    public static implicit operator BorderBl(Expr<Border> v) { return new BorderBl(v); }
    static BorderBl() {
      //CornerRadiusArity.CheckInit();
    }
    public BrushBl Background {
      get { return Provider.Property<Border,Brush>(System.Windows.Controls.Border.BackgroundProperty); }
      set { Background.Bind = value; }
    }
    public CornerRadiusBl CornerRadius {
      get {
        var e0 = (Provider.Property<Border,CornerRadius>(System.Windows.Controls.Border.CornerRadiusProperty));
        Double4Bl e1 = e0.ToBling();
        return (CornerRadiusBl)e1;
      }
      set {
        var e0 = (Provider.Property<Border,CornerRadius>(System.Windows.Controls.Border.CornerRadiusProperty));
        Double4Bl e1 = e0.ToBling();
        e1.Bind = (Double4Bl)value;
      }
    }
    /// <summary>
    /// Get and set border properties.
    /// </summary>
    public BorderInfoSet Border {
      get {
        return new BorderInfo<Border> {
          Underlying = Provider,
          BorderBrushProperty = System.Windows.Controls.Border.BorderBrushProperty,
          BorderThicknessProperty = System.Windows.Controls.Border.BorderThicknessProperty,
        };
      }
      set {
        Border.Bind(value);
      }
    }
  }
  /// <summary>
  ///     Represents a pop-up window that has content.
  /// </summary>
  public class PopupBl : FrameworkElementBl<Popup, PopupBl> {
    public PopupBl(Expr<Popup> Provider) : base(Provider) { }
    public PopupBl() : base(new Constant<Popup>(new Popup())) { }
    public static implicit operator PopupBl(Expr<Popup> v) { return new PopupBl(v); }
    public static implicit operator PopupBl(Popup v) { return new Constant<Popup>(v); }
    /// <summary>
    ///     Gets or sets a value that indicates whether a System.Windows.Controls.Primitives.Popup
    ///     control can contain transparent content. This is a dependency property. The default is false.
    /// </summary>
    public BoolBl AllowsTransparency {
      get { return Provider.Property<Popup, bool>(Popup.AllowsTransparencyProperty); }
      set { AllowsTransparency.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the content of the System.Windows.Controls.Primitives.Popup
    ///     control. This is a dependency property. The default is null.
    /// </summary>
    public FrameworkElementBl Child {
      get { return Provider.Property<Popup,UIElement>(Popup.ChildProperty); }
      set { Child.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a delegate handler method that positions the System.Windows.Controls.Primitives.Popup
    ///     control. This is a dependency property. The default is null.
    /// </summary>
    // public CustomPopupPlacementCallback CustomPopupPlacementCallback { get; set; }

    /// <summary>
    ///     Gets a value that indicates whether a System.Windows.Controls.Primitives.Popup
    ///     is displayed with a drop shadow effect. This is a dependency property.
    /// </summary>
    public BoolBl HasDropShadow {
      get { return Provider.Property<Popup, bool>(Popup.HasDropShadowProperty); }
    }
    /// <summary>
    ///     Get or sets the distance between the target origin and the popup
    ///     alignment point. This is a dependency property. For information about the target origin and popup alignment point,
    ///     see Popup Placement Behavior. The default is 0,0.
    /// </summary>
    public Double2Bl Offset {
      get {
        DoubleBl h = Provider.Property<Popup,double>(Popup.HorizontalAlignmentProperty);
        DoubleBl v = Provider.Property<Popup,double>(Popup.VerticalAlignmentProperty);
        return new Double2Bl(h, v);
      }
      set { Offset.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value that indicates whether the System.Windows.Controls.Primitives.Popup
    ///     is visible. This is a dependency property. The default is false.
    /// </summary>
    public BoolBl IsOpen {
      get { return Provider.Property<Popup, bool>(Popup.IsOpenProperty); }
      set { IsOpen.Bind = value; }
    }
    public class PlacementSet {
      internal Expr<Popup> Underlying;
      /// <summary>
      ///     Gets or sets the orientation of the System.Windows.Controls.Primitives.Popup
      ///     control when the control opens, and specifies the behavior of the System.Windows.Controls.Primitives.Popup
      ///     control when it overlaps screen boundaries. This is a dependency property. 
      /// The default is System.Windows.Controls.Primitives.PlacementMode.Bottom.
      /// </summary>
      public EnumBl<PlacementMode> Mode {
        get { return Underlying.Property<Popup,PlacementMode>(Popup.PlacementProperty); }
        set { Mode.Bind = value; }
      }
      /// <summary>
      ///     Gets or sets the rectangle relative to which the System.Windows.Controls.Primitives.Popup
      ///     control is positioned when it opens. This is a dependency property. The default is null.
      /// </summary>
      public Double4Bl Rectangle {
        get { return Underlying.Property<Popup,Rect>(Popup.PlacementRectangleProperty); }
        set { Rectangle.Bind = value; }
      }
      /// <summary>
      ///     Gets or sets the element relative to which the System.Windows.Controls.Primitives.Popup
      ///     is positioned when it opens. This is a dependency property. The default is null.
      /// </summary>
      public FrameworkElementBl Target {
        get { return Underlying.Property<Popup,UIElement>(Popup.PlacementTargetProperty); }
        set { Target.Bind = value; }
      }
      internal PlacementSet Bind {
        set {
          Mode.Bind = value.Mode; Rectangle.Bind = value.Rectangle;
          Target.Bind = value.Target;
        }
      }
    }
    /// <summary>
    ///     Gets or sets the mode, rectangle, and target relative to which the System.Windows.Controls.Primitives.Popup
    ///     control is positioned when it opens. This is a dependency property. 
    /// </summary>
    public PlacementSet Placement {
      get { return new PlacementSet() { Underlying = Provider }; }
      set { Placement.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets an animation for the opening and closing of a System.Windows.Controls.Primitives.Popup
    ///     control. This is a dependency property. The default is System.Windows.Controls.Primitives.PopupAnimation.None.
    /// </summary>
    public EnumBl<PopupAnimation> PopupAnimation {
      get { return Provider.Property<Popup,PopupAnimation>(Popup.PopupAnimationProperty); }
      set { PopupAnimation.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value that indicates whether the System.Windows.Controls.Primitives.Popup
    ///     control closes when the control is no longer in focus. This is a dependency
    ///     property. The default is true.
    /// </summary>
    public BoolBl StaysOpen {
      get { return Provider.Property<Popup,bool>(Popup.StaysOpenProperty); }
      set { StaysOpen.Bind = value; }
    }
  }

  public class WindowBl : ContentControlBl<Window, WindowBl> {
    public WindowBl(Expr<Window> Provider) : base(Provider) { }
    public WindowBl() : base(new Constant<Window>(new Window())) { }
    static WindowBl() {
    }
    public static implicit operator WindowBl(Expr<Window> v) { return new WindowBl(v); }
    public static implicit operator WindowBl(Window  v) { return new Constant<Window>(v); }


    /// <summary>
    ///     Gets or sets the System.Windows.Window that owns this System.Windows.Window. This is not a dependency property.
    /// </summary>
    public WindowBl Owner {
      get { return CurrentValue.Owner; }
      set { CurrentValue.Owner = value.CurrentValue; }
    }

    public BoolBl AllowsTransparency {
      get { return Provider.Property<Window,bool>(Window.AllowsTransparencyProperty).Bl(); }
      set { AllowsTransparency.Bind = value; }
    }
    public BoolBl ShowInTaskbar {
      get { return Provider.Property<Window, bool>(Window.ShowInTaskbarProperty).Bl(); }
      set { ShowInTaskbar.Bind = value; }
    }
    public BoolBl IsActive {
      get { return Provider.Property<Window, bool>(Window.IsActiveProperty).Bl(); }
      set { IsActive.Bind = value; }
    }
    public BoolBl Topmost {
      get { return Provider.Property<Window, bool>(Window.TopmostProperty).Bl(); }
      set { Topmost.Bind = value; }
    }
    public override DoubleBl Left {
      get { return Provider.Property<Window, double>(Window.LeftProperty).Bl(); }
      set { this.Left = value; }
    }
    public override DoubleBl Top {
      get { return Provider.Property<Window, double>(Window.TopProperty).Bl(); }
      set { this.Top = value; }
    }
    public StringBl Title {
      get { return Provider.Property<Window, string>(Window.TitleProperty); }
      set { Title.Bind = value; }
    }
    public EnumBl<WindowStyle> WindowStyle {
      get { return Provider.Property<Window, WindowStyle>(Window.WindowStyleProperty); }
      set { WindowStyle.Bind = value; }
    }
    public EnumBl<WindowState> WindowState {
      get { return Provider.Property<Window, WindowState>(Window.WindowStateProperty); }
      set { WindowState.Bind = value; }
    }
    /// <summary>
    /// Gets or sets a value that indicates whether a window will automatically size
    /// itself to fit the size of its content. This is a dependency property. 
    /// The default is System.Windows.SizeToContent.Manual.
    /// </summary>
    public EnumBl<SizeToContent> SizeToContent {
      get { return Provider.Property<Window, SizeToContent>(Window.SizeToContentProperty); }
      set { SizeToContent.Bind = value; }
    }
    /// <summary>
    ///     Manually closes a System.Windows.Window.
    /// </summary>
    public Command Close {
      get {
        var wF = AsFunc;
        return new Command("Close", () => wF().Close()); }
    }
    /// <summary>
    ///     Opens a window and returns without waiting for the newly opened window to
    ///     close.
    ///
    /// </summary>
    /// <exception cref="System.InvalidOperationException">System.Windows.Window.Show() is called on a window that is closing (System.Windows.Window.Closing)
    ///    or has been closed (System.Windows.Window.Closed)
    ///</exception>
    public Command Show {
      get {
        var wF = AsFunc;
        return new Command("Show", () => wF().Show());
      }
    }
    /// <summary>
    ///  Opens a window and returns only when the newly opened window is closed.    
    /// </summary>
    public Command ShowDialog {
      get {
        var wF = AsFunc;
        return new Command("ShowDialog", () => wF().ShowDialog());
      }
    }

  }


  /// <summary>
  /// Represents a scrollable area that can contain other visible elements.
  /// </summary>
  public class ScrollViewerBl : ContentControlBl<ScrollViewer, ScrollViewerBl> {
    public ScrollViewerBl(Expr<ScrollViewer> Provider) : base(Provider) {}
    public ScrollViewerBl(PanelBl canvas) : base(canvas, new ScrollViewer()) { }
    public ScrollViewerBl() : base() { }
    static ScrollViewerBl() { }
    public static implicit operator ScrollViewerBl(Expr<ScrollViewer> v) { return new ScrollViewerBl(v); }

    /// <summary>
    /// Gets or sets a value that indicates whether elements that support the System.Windows.Controls.Primitives.IScrollInfo
    /// interface are allowed to scroll.
    /// </summary>
    public BoolBl CanContentScroll {
      get { return Provider.Property<ScrollViewer, bool>(ScrollViewer.CanContentScrollProperty).Bl(); }
      set { CanContentScroll.Bind = value; }
    }
    public Double2Bl ContentOffset {
      get {
        var x = Provider.Property<ScrollViewer,double>(ScrollViewer.ContentHorizontalOffsetProperty).Bl();
        var y = Provider.Property<ScrollViewer, double>(ScrollViewer.ContentVerticalOffsetProperty).Bl();
        return new Double2Bl(x, y);
      }
    }
    /// <summary>
    /// Gets a value that contains the horizontal and the horizontal offset of the scrolled content.
    /// </summary>
    public Double2Bl Offset {
      get {
        var x = Provider.Property<ScrollViewer, double>(ScrollViewer.HorizontalOffsetProperty).Bl();
        var y = Provider.Property<ScrollViewer, double>(ScrollViewer.VerticalOffsetProperty).Bl();
        return new Double2Bl(x, y);
      }
    }
    /// <summary>
    /// Gets a value that contains the vertical and the horizontal  size of the extent
    /// </summary>
    public Double2Bl ExtentSize {
      get {
        var x = Provider.Property<ScrollViewer, double>(ScrollViewer.ExtentWidthProperty).Bl();
        var y = Provider.Property<ScrollViewer, double>(ScrollViewer.ExtentHeightProperty).Bl();
        return new Double2Bl(x, y);
      }
    }
    /// <summary>
    /// Gets a value that represents the vertical and the horizontal  size of the content element that
    /// can be scrolled.
    /// </summary>
    public Double2Bl ScrollableSize {
      get {
        var x = Provider.Property<ScrollViewer, double>(ScrollViewer.ScrollableWidthProperty).Bl();
        var y = Provider.Property<ScrollViewer, double>(ScrollViewer.ScrollableHeightProperty).Bl();
        return new Double2Bl(x, y);
      }
    }
    /// <summary>
    /// Gets a value that contains the vertical and the horizontal size of the content's viewport
    /// </summary>
    public Double2Bl ViewportSize {
      get {
        var x = Provider.Property<ScrollViewer, double>(ScrollViewer.ViewportWidthProperty).Bl();
        var y = Provider.Property<ScrollViewer, double>(ScrollViewer.ViewportHeightProperty).Bl();
        return new Double2Bl(x, y);
      }
    }
    /// <summary>
    /// Get the Visibility of ScrollBar
    /// </summary>
    public OrientationX<ScrollViewer, ScrollBarVisibility, EnumBl<ScrollBarVisibility>> ScrollBarVisibility {
      get {
        return new OrientationX<ScrollViewer, ScrollBarVisibility, EnumBl<ScrollBarVisibility>>() {
          Provider = Provider, HorizontalProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty,
          VerticalProperty = ScrollViewer.VerticalScrollBarVisibilityProperty,
        };
      }
    }
    /// <summary>
    /// Get the Visibility of Computed ScrollBar
    /// </summary>
    public OrientationX<ScrollViewer, Visibility, VisibilityBl> ComputedScrollBarVisibility {
      get {
        return new OrientationX<ScrollViewer, Visibility, VisibilityBl>() {
          Provider = Provider, HorizontalProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty,
          VerticalProperty = ScrollViewer.VerticalScrollBarVisibilityProperty,
        };
      }
    }
  }
  public class OrientationX<TARGET, T, SELF> where SELF : ValueBrand<T,SELF> where TARGET : DependencyObject {
    public Expr<TARGET> Provider;
    public DependencyProperty HorizontalProperty;
    public DependencyProperty VerticalProperty;
    public SELF this[OrientationBl orientation] {
      get {
        SELF h = Brand<T, SELF>.ToBrand(Provider.Property<TARGET,T>(HorizontalProperty));
        SELF v = Brand<T, SELF>.ToBrand(Provider.Property<TARGET, T>(VerticalProperty));
        return (orientation == Orientation.Horizontal).Condition<SELF>(h, v);
      }
      set {
        this[orientation].Bind = value;
      }
    }
    /// <summary>
    /// Gets or sets the value of HorizontalProperty
    /// </summary>
    public SELF Horizontal {
      get { return Brand<T, SELF>.ToBrand(Provider.Property<TARGET,T>(HorizontalProperty)); }
      set { Horizontal.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the value of VerticalProperty
    /// </summary>
    public SELF Vertical {
      get { return Brand<T, SELF>.ToBrand(Provider.Property<TARGET, T>(VerticalProperty)); }
      set { Vertical.Bind = value; }
    }
    public SELF X { get { return Horizontal; } set { X.Bind = value; } }
    public SELF Y { get { return Horizontal; } set { X.Bind = value; } }

  }

  /// <summary>
  /// Base class for controls that can switch states, such as System.Windows.Controls.CheckBox.
  /// </summary>
  /// <typeparam name="TARGET"></typeparam>
  public abstract partial class ToggleButtonBl<T,SELF> : ButtonBaseBl<T,SELF> where T : ToggleButton where SELF : ToggleButtonBl<T,SELF> {
    public ToggleButtonBl(Expr<T> Provider) : base(Provider) { }
    public ToggleButtonBl() : base() { }
    public ToggleButtonBl(PanelBl canvas, T target) : base(canvas, target) { }
    /// <summary>
    ///    Gets or sets whether the System.Windows.Controls.Primitives.ToggleButton
    ///     is checked. This is a dependency property.
    /// </summary>
    /// <returns>
    ///    true if the System.Windows.Controls.Primitives.ToggleButton is checked; false
    ///     if the System.Windows.Controls.Primitives.ToggleButton is unchecked; otherwise
    ///     null. The default is false.
    ///</returns>    
    public BoolBl IsChecked {
      get { return Provider.Property<T,bool>(ToggleButton.IsCheckedProperty).Bl(); }
      set { IsChecked.Bind = value; }
    }
    public Action Checked {
      set { Provider.CurrentValue.Checked += (x, y) => value(); }
    }
    public Action Unchecked {
      set { Provider.CurrentValue.Unchecked += (x, y) => value(); }
    }
    public BoolBl IsThreeState {
      get { return Provider.Property<T,bool>(ToggleButton.IsThreeStateProperty); }
      set { IsThreeState.Bind = value; }
    }
    public static implicit operator BoolBl(ToggleButtonBl<T, SELF> t) { return t.IsChecked; }
    public static implicit operator DoubleBl(ToggleButtonBl<T, SELF> t) { 
      return t.IsChecked.Condition(1d,0d); 
    }
    public static BoolBl operator !(ToggleButtonBl<T, SELF> t) {
      return !t.IsChecked;
    }

  }
  /// <summary>
  /// Bl wrapper around a checkbox that epresents a control that a user can select and clear.
  /// </summary>
  public partial class CheckBoxBl : ToggleButtonBl<CheckBox, CheckBoxBl> {
    public CheckBoxBl(Expr<CheckBox> Provider) : base(Provider) { }
    public CheckBoxBl(PanelBl canvas) : base(canvas, new CheckBox()) { }
    public CheckBoxBl() : base(new CheckBox()) { }
    public static implicit operator CheckBoxBl(Expr<CheckBox> v) { return new CheckBoxBl(v); }
    public static implicit operator CheckBoxBl(CheckBox v) { return (new Constant<CheckBox>(v)); }

    static CheckBoxBl() {
    }
  }
  /// <summary>
  ///     Represents a button that can be selected, but not cleared, by a user. The
  ///     System.Windows.Controls.Primitives.ToggleButton.IsChecked property of a System.Windows.Controls.RadioButton
  ///     can be set by clicking it, but it can only be cleared programmatically.
  /// </summary>
  public partial class RadioButtonBl : ToggleButtonBl<RadioButton, RadioButtonBl> {
    public RadioButtonBl(Expr<RadioButton> Provider) : base(Provider) { }
    public RadioButtonBl() : base(new RadioButton()) { }
    public RadioButtonBl(PanelBl canvas) : base(canvas, new RadioButton()) { }
    public static implicit operator RadioButtonBl(Expr<RadioButton> v) { return new RadioButtonBl(v); }
    public static implicit operator RadioButtonBl(RadioButton v) { return (new Constant<RadioButton>(v)); }
    static RadioButtonBl() {
    }
    /// <summary>
    ///     Gets or sets the name that specifies which System.Windows.Controls.RadioButton
    ///     controls are mutually exclusive. This is a dependency property. The default is an empty string.
    /// </summary>
    public StringBl GroupName {
      get { return Provider.Property<RadioButton,string>(RadioButton.GroupNameProperty); }
      set { GroupName.Bind = value; }
    }

  }

  /// <summary>
  ///     Provides a base class for all System.Windows.Controls.Panel elements. Use
  ///     System.Windows.Controls.Panel elements to position and arrange child objects
  ///     in Windows Presentation Foundation (WPF) applications.
  /// </summary>
  public abstract partial class PanelBl<T, SELF> : FrameworkElementBl<T, SELF>, IExtends<SELF,PanelBl>
    where T : Panel
    where SELF : PanelBl<T, SELF> {
    public PanelBl(Expr<T> Provider) : base(Provider) { }
    public PanelBl() : base() { }
    public PanelBl(PanelBl canvas, T target) : base(canvas, target) { }

    public static implicit operator PanelBl(PanelBl<T, SELF> canvas) {
      return PanelBl.UpCast(canvas);
    }
   

    /// <summary>
    ///    Gets or sets a System.Windows.Media.Brush that is used to fill the area between
    ///     the borders of a System.Windows.Controls.Panel. This is a dependency property.
    /// </summary>
    /// <returns>
    ///    A System.Windows.Media.Brush. This default value is null.
    ///</returns>    
    public BrushBl Background {
      get { return Provider.Property<T,Brush>(Canvas.BackgroundProperty).Bl(); }
      set { Background.Bind = value; }
    }
    /// <summary>
    ///     Gets a System.Windows.Controls.UIElementCollection of child elements of this
    ///     System.Windows.Controls.Panel.    
    /// </summary>
    public UIElementCollection Children {
      get { return CurrentValue.Children; }
    }
  }
  public abstract partial class ContentElementBl<T, BRAND> : Brand<T, BRAND>, IDependencyObjectBl<T, BRAND>
    where T : ContentElement
    where BRAND : ContentElementBl<T, BRAND> {
    public ContentElementBl(Expr<T> Provider) : base(Provider) { }
    public ContentElementBl() : base() { }

  }
  public abstract partial class FrameworkContentElementBl<T, BRAND> : ContentElementBl<T, BRAND>
    where T : FrameworkContentElement
    where BRAND : FrameworkContentElementBl<T, BRAND> {
    public FrameworkContentElementBl(Expr<T> Provider) : base(Provider) { }
    public FrameworkContentElementBl() : base() { }

  }

  public partial class GridBl : PanelBl<Grid, GridBl> {
    public GridBl(Expr<Grid> Provider) : base(Provider) { }
    public GridBl() : base(new Grid()) { }
    public GridBl(PanelBl canvas, Grid target) : base(canvas, target) { }
    public GridBl(PanelBl canvas) : base(canvas, new Grid()) { }
    /// <summary>
    /// Gets or sets a value that indicates whether grid lines are visible within
    /// this grid. This is a dependency property.
    /// </summary>
    public BoolBl ShowGridLines {
      get { return Provider.Property<Grid, bool>(Grid.ShowGridLinesProperty); }
      set { ShowGridLines.Bind = value; }
    }
    public partial class LengthBl : ValueBrand<GridLength, LengthBl> {

    }


    public class DefinitionBaseBl<T, BRAND> : FrameworkContentElementBl<T, BRAND>
      where T : DefinitionBase
      where BRAND : DefinitionBaseBl<T, BRAND> {
          public DefinitionBaseBl(Expr<T> Provider) : base(Provider) { }
          public DefinitionBaseBl() : base() { }

    }
  }
  public abstract partial class FrameworkElementBl<T, BRAND> : UIElementBl<T, BRAND>, IExtends<BRAND, FrameworkElementBl>
    where T : FrameworkElement
    where BRAND : FrameworkElementBl<T, BRAND> {

    public IntBl Column {
      get { return Provider.Property<T, int>(Grid.ColumnProperty); }
      set { Column.Bind = value; }
    }
    public IntBl ColumnSpan {
      get { return Provider.Property<T, int>(Grid.ColumnSpanProperty); }
      set { ColumnSpan.Bind = value; }
    }
    public IntBl Row {
      get { return Provider.Property<T, int>(Grid.RowProperty); }
      set { Row.Bind = value; }
    }
    public IntBl RowSpan {
      get { return Provider.Property<T, int>(Grid.RowSpanProperty); }
      set { RowSpan.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the outer margin of an element. This is a dependency property.
    ///     
    /// Returns
    ///     margin values for the element. The default value is a System.Windows.Thickness
    ///     with all properties equal to 0 (zero).
    /// </summary>
    public ThicknessBl Margin {
      get { return Provider.Property<T, Thickness>(FrameworkElement.MarginProperty); }
      set {
        var d = Provider.Property<T, Thickness>(FrameworkElement.MarginProperty).ToBling().Bl();
        d.Bind = value.All;
      }
    }
  }
  

  


  /// <summary>
  ///     Provides a base class for all System.Windows.Controls.Panel elements. Use
  ///     System.Windows.Controls.Panel elements to position and arrange child objects
  ///     in Windows Presentation Foundation (WPF) applications.
  /// </summary>
  public sealed partial class PanelBl : PanelBl<Panel,PanelBl> {
    public PanelBl(Expr<Panel> Provider) : base(Provider) { }
    public PanelBl() : base() { }
    public static implicit operator PanelBl(Panel target) { return new PanelBl(new Constant<Panel>(target)); }
    public static implicit operator PanelBl(Expr<Panel> target) { return new PanelBl((target)); }
  }

  public abstract partial class ItemsControlBl<T,SELF> : ControlBl<T,SELF> where T : ItemsControl where SELF : ItemsControlBl<T,SELF> {
    public ItemsControlBl(Expr<T> Underlying) : base(Underlying) { }
    public ItemsControlBl() : base() { }
    public ItemsControlBl(PanelBl canvas, T target) : base(canvas, target) { }
    /// <summary>
    ///     Gets the collection used to generate the content of the System.Windows.Controls.ItemsControl.
    /// </summary>
    /// <returns>
    ///     The collection that is used to generate the content of the System.Windows.Controls.ItemsControl.
    ///     The default is an empty collection.
    /// </returns>
    public ItemCollection Items {
      get { return CurrentValue.Items; }
    }
    /// <summary>
    ///     Gets or sets number of alternating item containers in the System.Windows.Controls.ItemsControl,
    ///     which enables alternating containers to have a unique appearance.
    /// </summary>
    /// <returns>
    ///     The number of alternating item containers in the System.Windows.Controls.ItemsControl.
    /// </returns>
    public IntBl AlternationCount { get { return Provider.Property<T,int>(ItemsControl.AlternationCountProperty); } set { AlternationCount.Bind = value; } }
    /// <summary>
    ///     Gets or sets a path to a value on the source object to serve as the visual
    ///     representation of the object. This is a dependency property.
    /// </summary>
    /// <returns>
    ///     The path to a value on the source object. This can be any path, or an XPath
    ///     such as "@Name". The default is an empty string ("").
    /// </returns>
    public StringBl DisplayMemberPath { get { return Provider.Property<T, string>(ItemsControl.DisplayMemberPathProperty); } set { DisplayMemberPath.Bind = value; } }
    /// <summary>
    ///     Gets a value that indicates whether the System.Windows.Controls.ItemsControl
    ///     contains items. This is a dependency property.
    /// </summary>
    /// <returns>
    ///     true if the items count is greater than 0; otherwise, false.The default is
    ///     false.
    /// </returns>
    public BoolBl HasItems { get { return Provider.Property<T,bool>(ItemsControl.HasItemsProperty); } }
    /// <summary>
    ///     Gets a value that indicates whether the control is using grouping. This is
    ///     a dependency property.
    /// </summary>
    /// <returns>
    ///     true if a control is using grouping; otherwise, false.
    /// </returns>
    public BoolBl IsGrouping { get { return Provider.Property<T,bool>(ItemsControl.IsGroupingProperty); } }
    /// <summary>
    ///     Gets or sets a value that indicates whether System.Windows.Controls.TextSearch
    ///     is enabled on the System.Windows.Controls.ItemsControl instance. This is
    ///     a dependency property.
    /// </summary>
    /// <returns>
    ///     true if System.Windows.Controls.TextSearch is enabled; otherwise, false.
    ///     The default is false.
    /// </returns>
    public BoolBl IsTextSearchEnabled { get { return Provider.Property<T,bool>(ItemsControl.IsTextSearchEnabledProperty); } set { IsTextSearchEnabled.Bind = value; } }
    /// <summary>
    ///     Gets or sets a composite string that specifies how to format the items in
    ///     the System.Windows.Controls.ItemsControl if they are displayed as strings.
    /// </summary>
    /// <returns>
    ///     A composite string that specifies how to format the items in the System.Windows.Controls.ItemsControl
    ///     if they are displayed as strings.
    /// </returns>
    public StringBl ItemStringFormat { get { return Provider.Property<T, string>(ItemsControl.ItemStringFormatProperty); } set { ItemStringFormat.Bind = value; } }

  }
  public abstract partial class SelectorBl<T, SELF> : ItemsControlBl<T, SELF>
    where T : Selector
    where SELF : SelectorBl<T, SELF> {
    public SelectorBl(Expr<T> Underlying) : base(Underlying) { }
    public SelectorBl() : base() { }
    public SelectorBl(PanelBl canvas, T target) : base(canvas, target) { }
    /// <summary>
    ///      Gets or sets a value that indicates whether a System.Windows.Controls.Primitives.Selector
    ///     should keep the System.Windows.Controls.Primitives.Selector.SelectedItem
    ///     synchronized with the current item in the System.Windows.Controls.ItemsControl.Items
    ///     property. This is a dependency property.
    /// </summary>
    public BoolBl IsSynchronizedWithCurrentItem {
      get {
        var p = Provider.Property<T, bool?>(Selector.IsSynchronizedWithCurrentItemProperty);
        return new Ops.MapOperator<bool?, bool>(b => b != null && ((bool)b)) { G = b => b }.Make(p);
      }
      set { IsSynchronizedWithCurrentItem.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets the index of the first item in the current selection or returns
    ///     negative one (-1) if the selection is empty. This is a dependency property.
    /// </summary>
    public IntBl SelectedIndex { get { return Provider.Property<T, int>(Selector.SelectedIndexProperty); } set { SelectedIndex.Bind = value; } }
    /// <summary>
    ///     Gets or sets the first item in the current selection or returns null if the
    ///     selection is empty This is a dependency property.
    /// </summary>
    public ObjectBl SelectedItem { get { return Provider.Property<T, object>(Selector.SelectedItemProperty); } set { SelectedItem.Bind = value; } }
    /// <summary>
    ///     Gets or sets the value of the System.Windows.Controls.Primitives.Selector.SelectedItem,
    ///     obtained by using System.Windows.Controls.Primitives.Selector.SelectedValuePath.
    ///     This is a dependency property.
    /// </summary>
    public ObjectBl SelectedValue { get { return Provider.Property<T, object>(Selector.SelectedValueProperty); } set { SelectedValue.Bind = value; } }
    /// <summary>
    ///     Gets or sets the path that is used to get the System.Windows.Controls.Primitives.Selector.SelectedValue
    ///     from the System.Windows.Controls.Primitives.Selector.SelectedItem. This is
    ///     a dependency property.
    /// </summary>
    public StringBl SelectedValuePath { get { return Provider.Property<T, string>(Selector.SelectedValuePathProperty); } set { SelectedValuePath.Bind = value; } }

  }
  /// <summary>
  ///     Contains a list of selectable items.
  /// </summary>
  public partial class ListBoxBl : SelectorBl<ListBox, ListBoxBl> {
    public ListBoxBl(Expr<ListBox> Underlying) : base(Underlying) { }
    public ListBoxBl() : base(new ListBox()) { }
    public ListBoxBl(PanelBl Parent) : base(Parent, new ListBox()) { }
    /// <summary>
    ///     Gets the currently selected items. This is a dependency property.
    /// </summary>
    public CollectionBl<object, ObjectBl, System.Collections.IList> SelectedItems { get { return Provider.Property<ListBox,System.Collections.IList>(ListBox.SelectedItemsProperty); } }
    /// <summary>
    ///     Gets or sets the selection behavior for a System.Windows.Controls.ListBox.
    ///     This is a dependency property. The default is System.Windows.Controls.SelectionMode.Single
    ///     selection.
    /// </summary>
    public EnumBl<SelectionMode> SelectionMode { get { return Provider.Property<ListBox, SelectionMode>(ListBox.SelectionModeProperty); } set { SelectionMode.Bind = value; } }
  }
  /// <summary>
  ///     Represents a selection control with a drop-down list that can be shown or
  ///     hidden by clicking the arrow on the control.
  /// </summary>
  public partial class ComboBoxBl : SelectorBl<ComboBox, ComboBoxBl> {
    public ComboBoxBl(Expr<ComboBox> Underlying) : base(Underlying) { }
    public ComboBoxBl(PanelBl Parent) : base(Parent, new ComboBox()) { }
    public ComboBoxBl() : base(new ComboBox()) { }

    /// <summary>
    ///     Gets or sets a value that indicates whether the drop-down for a combo box
    ///     is currently open. This is a dependency property. The default is false.
    /// </summary>
    public BoolBl IsDropDownOpen { get { return Provider.Property<ComboBox, bool>(ComboBox.IsDropDownOpenProperty); } set { IsDropDownOpen.Bind = value; } }
    /// <summary>
    ///     Gets or sets a value that enables or disables editing of the text in text
    ///     box of the System.Windows.Controls.ComboBox. This is a  dependency property. The default is false.
    /// </summary>
    public BoolBl IsEditable { get { return Provider.Property<ComboBox, bool>(ComboBox.IsEditableProperty); } set { IsEditable.Bind = value; } }
    /// <summary>
    ///     Gets or sets a value that enables selection-only mode, in which the contents
    ///     of the combo box are selectable but not editable. This is a dependency property. The default is false.
    /// </summary>
    public BoolBl IsReadOnly { get { return Provider.Property<ComboBox, bool>(ComboBox.IsReadOnlyProperty); } set { IsReadOnly.Bind = value; } }
    
    /// <summary>
    ///     Gets whether the System.Windows.Controls.ComboBox.SelectionBoxItem is highlighted.
    /// </summary>
    //public BoolBl IsSelectionBoxHighlighted { get { return Underlying.Property<T,bool>(ComboBox.IsSe); } }
    
    /// <summary>
    ///     Gets or sets the maximum height for a combo box drop-down. This is a dependency
    ///     property.    The default value as defined to the property system is a calculated value
    ///     based on taking a one-third fraction of the system max screen height parameters,
    ///     but this default is potentially overridden by various control templates.
    /// </summary>
    public DoubleBl MaxDropDownHeight { get { return Provider.Property<ComboBox,double>(ComboBox.MaxDropDownHeightProperty); } set { MaxDropDownHeight.Bind = value; } }
    /// <summary>
    ///     Gets the item that is displayed in the selection box. This is a dependency
    ///     property.
    /// </summary>
    public ObjectBl SelectionBoxItem { get { return Provider.Property<ComboBox, object>(ComboBox.SelectionBoxItemProperty); } }
    /// <summary>
    ///     Gets a composite string that specifies how to format the selected item in
    ///     the selection box if it is displayed as a string.
    /// </summary>
    public StringBl SelectionBoxItemStringFormat { get { return Provider.Property<ComboBox, string>(ComboBox.SelectionBoxItemStringFormatProperty); } }
    
    /// <summary>
    ///     Gets the item template of the selection box content. This is a dependency
    ///     property.
    /// </summary>
    //public DataTemplate SelectionBoxItemTemplate { get; }
    
    /// <summary>
    ///     Gets or sets whether a System.Windows.Controls.ComboBox that is open and
    ///     displays a drop-down control will remain open when a user clicks the System.Windows.Controls.TextBox.
    ///     This is a dependency property. True to keep the drop-down control open when the user clicks on the text
    ///     area to start editing; otherwise, false. The default is false.
    /// </summary>
    public BoolBl StaysOpenOnEdit { get { return Provider.Property<ComboBox, bool>(ComboBox.StaysOpenOnEditProperty); } set { StaysOpenOnEdit.Bind = value; } }
    /// <summary>
    ///     Gets or sets the text of the currently selected item. This is a dependency
    ///     property. The default is an empty string
    ///     ("").
    /// </summary>
    public StringBl Text { get { return Provider.Property<ComboBox, string>(ComboBox.TextProperty); } set { Text.Bind = value; } }
  }




  public abstract partial class CanvasBl<T, BRAND> : PanelBl<T, BRAND>, IExtends<BRAND,CanvasBl>
    where T : Canvas
    where BRAND : CanvasBl<T, BRAND> {
    public CanvasBl(Expr<T> Provider) : base(Provider) { }
    public CanvasBl() : base() { }
    public CanvasBl(PanelBl canvas, T target) : base(canvas, target) { }
    public void Add(params FrameworkElementBl[] es) {
      foreach (var e in es) e.PanelParent = this;
    }
    public static implicit operator CanvasBl(CanvasBl<T, BRAND> canvas) {
      var result = CanvasBl.UpCast(canvas);
      return result;
    }
    static CanvasBl() {  }


    public LinearGradientBrushBl MakeInnerBorder(ColorBl start, ColorBl stop, Double2Bl thickness) {
      var Content = this;
      Func<Orientation, bool, LinearGradientBrushBl> MakeShade = (orient, isEnd) => {
        var rect = new RectangleBl(Content) {
          ZIndex = 1, IsHitTestVisible = false,
          Left = new Double2Bl(!isEnd ? 0 : Content.Width - thickness.X, 0)[(int) orient],
          Top = new Double2Bl(0, !isEnd ? 0 : Content.Height - thickness.Y)[(int) orient],

          Size = new Double2Bl(new Double2Bl(thickness.Y, Content.Width)[(int) orient],
                             new Double2Bl(Content.Height, thickness.X)[(int) orient]),
        };
        var brush = new LinearGradientBrushBl() {
          RelativeTransform = { Rotate = (90 * (new Double2Bl(isEnd ? -1 : +1, isEnd ? +1 : -1)[(int) orient])).Degrees() },
        }.Stop(start, 0).Stop(stop, 1);
        rect.Fill = brush;
        return brush;
      };
      LinearGradientBrushBl[] brushes = new LinearGradientBrushBl[] {
        MakeShade(Orientation.Horizontal, false),
        MakeShade(Orientation.Horizontal, true),
        MakeShade(Orientation.Vertical, false),
        MakeShade(Orientation.Vertical, true),
      };
      for (int i = 1; i < 4; i++) {
        brushes[i].MappingMode = brushes[0].MappingMode;
        brushes[i].Opacity = brushes[0].Opacity;
        brushes[i].SpreadMethod = brushes[0].SpreadMethod;
      }
      return brushes[0];
    }
  }
  public class RightSizeCanvasBl : CanvasBl<RightSizeCanvas, RightSizeCanvasBl> {
    public RightSizeCanvasBl(Expr<RightSizeCanvas> v) : base(v) { }
    public RightSizeCanvasBl(PanelBl Parent) : base(Parent, new RightSizeCanvas()) { }
    public static implicit operator RightSizeCanvasBl(Expr<RightSizeCanvas> v) { return new RightSizeCanvasBl(v); }
    public static implicit operator RightSizeCanvasBl(RightSizeCanvas v) { return new Constant<RightSizeCanvas>(v); }
    public Double2Bl AtSize {
      get { return CurrentValue.AtSize; }
    }

  }

  public class RightSizeCanvas : Canvas {

    public Double2Bl AtSize { get; private set; }
    private Double2Bl AtSize0 = new Double2Bl(0, 0);
    public RightSizeCanvas() {}
    protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved) {
      if (visualAdded != null && visualAdded is FrameworkElement) {
        FrameworkElementBl m = (FrameworkElement)visualAdded;
        AtSize = AtSize0;
        AtSize0 = (AtSize.Max(m.RightBottom));
        this.Bl().Size = AtSize0;
      }
      if (visualRemoved != null && visualRemoved is FrameworkElement) {
        throw new NotSupportedException();
      }
      base.OnVisualChildrenChanged(visualAdded, visualRemoved);
    }
  }
  /// <summary>
  ///     Defines an area within which you can explicitly position child elements by
  ///     using coordinates that are relative to the System.Windows.Controls.Canvas
  ///     area.
  /// </summary>
  public partial class CanvasBl : CanvasBl<Canvas, CanvasBl> {
    private CanvasBl(Expr<Canvas> Provider) : base(Provider) { }
    public CanvasBl() : this((Expr<Canvas>) new Constant<Canvas>(new Canvas())) { }
    public CanvasBl(PanelBl canvas) : base(canvas, new Canvas()) { }

    public static CanvasBl Make(Expr<Canvas> u) { return new CanvasBl(u); }

    public static implicit operator CanvasBl(Canvas target) { return new CanvasBl((Expr<Canvas>) new Constant<Canvas>(target)); }
    public static implicit operator CanvasBl(Expr<Canvas> target) { return new CanvasBl((target)); }
    /// <summary>
    /// No canvas, use when you want to remove an element from a canvas by assigning CanvasParent.
    /// </summary>
    public static CanvasBl None {
      get {
        if (((object)None0) == null) None0 = new CanvasBl(((Expr<Canvas>)new Constant<Canvas>(null)));
        return None0;
      }
    }
    private static CanvasBl None0;

    static CanvasBl() {
    }

  }

  public abstract class ImageSourceBl<T, BRAND> : Brand<T, BRAND>, IExtends<BRAND, ImageSourceBl>
    where T : ImageSource
    where BRAND : ImageSourceBl<T, BRAND> {
    public ImageSourceBl(Expr<T> underlying) : base(underlying) { }
    public ImageSourceBl() : base() { }
    public static implicit operator ImageSourceBl(ImageSourceBl<T, BRAND> source) {
      return ImageSourceBl.UpCast<BRAND>(source);
    }
    /// <summary>
    ///     When overridden in a derived class, gets the width of the image in measure
    ///     units (96ths of an inch).
    /// </summary>
    public DoubleBl Width {
      get { return CurrentValue.Width; }
    }
    /// <summary>
    ///     When overridden in a derived class, gets the height of the image in measure
    ///     units (96ths of an inch).
    /// </summary>
    public DoubleBl Height {
      get { return CurrentValue.Height; }
    }
    /// <summary>
    ///  Size of image source.
    /// </summary>
    public Double2Bl Size {
      get { return new Double2Bl(Width, Height); }
    }
  }


  /// <summary>
  ///     Represents a object type that has a width, height, and System.Windows.Media.ImageMetadata
  ///     such as a System.Windows.Media.Imaging.BitmapSource and a System.Windows.Media.DrawingImage.
  /// </summary>
  public class ImageSourceBl : ImageSourceBl<ImageSource, ImageSourceBl> {
    public ImageSourceBl(Expr<ImageSource> underlying) : base(underlying) { }
    public ImageSourceBl() : base() { }
    static ImageSourceBl() {
    }
    public static implicit operator ImageSourceBl(ImageSource Source) { return new ImageSourceBl(new Constant<ImageSource>(Source)); }
    //public static implicit operator ImageSourceBl(System.Drawing.Bitmap bitmap) { return bitmap.LoadBitmap(); }
    public static implicit operator ImageSourceBl(Expr<ImageSource> v) { return new ImageSourceBl(v); }

  }
  public class UriBl : Brand<Uri, UriBl> {
    public UriBl(Expr<Uri> underlying) : base(underlying) { }
    public UriBl() : base() { }
    public static implicit operator UriBl(Uri Source) { return new UriBl(new Constant<Uri>(Source)); }
    public static implicit operator UriBl(Expr<Uri> v) { return new UriBl(v); }
  }

  public class BitmapImageBl : ImageSourceBl<BitmapImage, BitmapImageBl> {
    public BitmapImageBl(Expr<BitmapImage> underlying) : base(underlying) { }
    public BitmapImageBl() : this(new Constant<BitmapImage>(new BitmapImage())) { }
    public static implicit operator BitmapImageBl(BitmapImage Source) { return new BitmapImageBl(new Constant<BitmapImage>(Source)); }
    public static implicit operator BitmapImageBl(Expr<BitmapImage> v) { return new BitmapImageBl(v); }

    public UriBl UriSource { 
      get { return Provider.Property<BitmapImage, Uri>(BitmapImage.UriSourceProperty); } 
      set { UriSource.Bind = value; } 
    }

  }


  /// <summary>
  ///     Represents a control that displays an image.
  /// </summary>
  public partial class ImageBl : FrameworkElementBl<Image,ImageBl> {
    public ImageBl(Expr<Image> Provider) : base(Provider) { }
    public ImageBl() : this(new Constant<Image>(new Image())) { }
    public ImageBl(PanelBl canvas) : base(canvas, new Image()) { }
    /// <summary>
    ///     The source of the drawn image. The default value is null.
    /// </summary>
    public ImageSourceBl Source {
      get { return Provider.Property<Image,ImageSource>(Image.SourceProperty); }
      set { Source.Bind = value; }
    }

    /// <summary>
    ///     Gets or sets a value that describes how an System.Windows.Controls.Image
    ///     should be stretched to fill the destination rectangle. This is a dependency
    ///     property. The default is System.Windows.Media.Stretch.Uniform.
    /// </summary>
    public EnumBl<Stretch> Stretch {
      get { return Provider.Property<Image,Stretch>(Image.StretchProperty); }
      set { Stretch.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value that indicates how the image is scaled. This is a dependency
    ///     property. The default is
    ///     System.Windows.Controls.StretchDirection.Both.
    /// </summary>
    public EnumBl<StretchDirection> StretchDirection {
      get { return Provider.Property<Image,StretchDirection>(Image.StretchDirectionProperty); }
      set { StretchDirection.Bind = value; }
    }

    public static implicit operator ImageBl(Expr<Image> v) { return new ImageBl(v); }
    public static implicit operator ImageBl(Image v) { return new Constant<Image>(v); }
  }
  public interface StrokeSet {
    /// <summary>
    ///     A System.Windows.Media.Brush that specifies how the System.Windows.Shapes.Shape
    ///     outline is painted. The default is null.
    /// </summary>
    BrushBl Brush { get; set; }
    /// <summary>
    ///     The width of the System.Windows.Shapes.Shape outline.
    /// </summary>
    DoubleBl Thickness { get; set; }
    /// <summary>
    /// This stroke's dash properties.
    /// </summary>
    DashSet Dash { get; set; }
    StrokeSet Bind { set; }
    /// <summary>
    /// The line properties of this stroke.
    /// </summary>
    LineSet Line { get; set; }
    /// <summary>
    ///     The limit on the ratio of the miter length to the System.Windows.Shapes.Shape.StrokeThickness
    ///     of a System.Windows.Shapes.Shape element. This value is always a positive
    ///     number that is greater than or equal to 1.
    /// </summary>
    DoubleBl MiterLimit { get; set;  }
  }
  public interface LineSet {
    /// <summary>
    ///     Gets or sets a System.Windows.Media.PenLineCap enumeration value that describes
    ///     the System.Windows.Shapes.Shape at the end of a line. The default
    ///     is System.Windows.Media.PenLineCap.Flat.
    /// </summary>
    EnumBl<PenLineCap> EndCap { get; set; }
    /// <summary>
    ///     Gets or sets a System.Windows.Media.PenLineJoin enumeration value that specifies
    ///     the type of join that is used at the vertices of a System.Windows.Shapes.Shape.
    /// </summary>
    EnumBl<PenLineJoin> Join { get; set; }
    /// <summary>
    ///     Gets or sets a System.Windows.Media.PenLineCap enumeration value that describes
    ///     the System.Windows.Shapes.Shape at the start of a System.Windows.Shapes.Shape.Stroke. The default
    ///     is System.Windows.Media.PenLineCap.Flat.
    /// </summary>
    EnumBl<PenLineCap> StartCap { get; set; }
    LineSet Bind { set; }
  }
  public interface DashSet {
    /// <summary>
    ///     A System.Double that represents the distance within the dash pattern where
    ///     a dash begins.
    /// </summary>
    DoubleBl Offset { get; set; }
    /// <summary>
    ///     A collection of System.Double values that specify the pattern of dashes and
    ///     gaps.
    /// </summary>
    DoubleCollectionBl Array { get; set; }
    /// <summary>
    ///     Gets or sets a System.Windows.Media.PenLineCap enumeration value that specifies
    ///     how the ends of a dash are drawn. The default
    ///     is System.Windows.Media.PenLineCap.Flat.
    /// </summary>
    EnumBl<PenLineCap> Cap { get; set; }
    DashSet Bind { set; }
  }

  /// <summary>
  /// Bl wrapper around a base class for shape elements
  /// </summary>
  public abstract partial class ShapeBl<T,SELF> : FrameworkElementBl<T,SELF> where T : Shape where SELF : ShapeBl<T,SELF> {
    public ShapeBl(Expr<T> Provider) : base(Provider) { }
    public ShapeBl() : base() { }
    public ShapeBl(PanelBl canvas, T shape)
      : base(canvas, shape) {
      this.Stroke.Brush = Brushes.Black;
      this.Stroke.Thickness = 1d;   
    }
    static ShapeBl() { ShapeBl.CheckInit(); }
    /// <summary>
    ///    Gets or sets the System.Windows.Media.Brush that specifies how the shape's
    ///     interior is painted.
    /// </summary>
    /// <returns>
    ///    A System.Windows.Media.Brush that describes how the shape's interior is painted.
    ///     The default is null.
    ///</returns>    
    public BrushBl Fill {
      get {

        return Provider.Property<T, Brush>(Shape.FillProperty).Bl();
      }
      set { Fill.Bind = value; }
    }
    private class StrokeSetImpl : StrokeSet {
      internal Expr<T> Underlying;
      /// <summary>
      ///     A System.Windows.Media.Brush that specifies how the System.Windows.Shapes.Shape
      ///     outline is painted. The default is null.
      /// </summary>
      public BrushBl Brush {
        get { return Underlying.Property<T, Brush>(Shape.StrokeProperty).Bl(); }
        set { Brush.Bind = value; }
      }
      /// <summary>
      ///     The width of the System.Windows.Shapes.Shape outline.
      /// </summary>
      public DoubleBl Thickness {
        get { return Underlying.Property<T, double>(Shape.StrokeThicknessProperty).Bl(); }
        set { Thickness.Bind = value; }
      }
      private class DashSetImpl : DashSet {
        internal Expr<T> Underlying;
        /// <summary>
        ///     A System.Double that represents the distance within the dash pattern where
        ///     a dash begins.
        /// </summary>
        public DoubleBl Offset {
          get { return Underlying.Property<T,double>(Shape.StrokeDashOffsetProperty).Bl(); }
          set { Offset.Bind = value; }
        }
        /// <summary>
        ///     A collection of System.Double values that specify the pattern of dashes and
        ///     gaps.
        /// </summary>
        public DoubleCollectionBl Array {
          get { return Underlying.Property<T,DoubleCollection>(Shape.StrokeDashArrayProperty); }
          set { Array.Bind = value; }
        }
        /// <summary>
        ///     Gets or sets a System.Windows.Media.PenLineCap enumeration value that specifies
        ///     how the ends of a dash are drawn. The default
        ///     is System.Windows.Media.PenLineCap.Flat.
        /// </summary>
        public EnumBl<PenLineCap> Cap {
          get { return Underlying.Property<T, PenLineCap>(Shape.StrokeDashCapProperty); }
          set { Cap.Bind = value; }
        }
        public DashSet Bind {
          set {
            this.Offset.Bind = value.Offset;
            this.Array.Bind = value.Array;
            this.Cap.Bind = value.Cap;
          }
        }
      }
      /// <summary>
      /// This stroke's dash properties.
      /// </summary>
      public DashSet Dash {
        get { return new DashSetImpl() { Underlying = Underlying }; }
        set { this.Dash.Bind = value; }
      }
      /// <summary>
      ///     The limit on the ratio of the miter length to the System.Windows.Shapes.Shape.StrokeThickness
      ///     of a System.Windows.Shapes.Shape element. This value is always a positive
      ///     number that is greater than or equal to 1.
      /// </summary>
      public DoubleBl MiterLimit {
        get { return Underlying.Property<T, double>(Shape.StrokeMiterLimitProperty); }
        set { MiterLimit.Bind = value; }
      }
      private class LineSetImpl : LineSet {
        internal Expr<T> Underlying;
        /// <summary>
        ///     Gets or sets a System.Windows.Media.PenLineCap enumeration value that describes
        ///     the System.Windows.Shapes.Shape at the end of a line. The default
        ///     is System.Windows.Media.PenLineCap.Flat.
        /// </summary>
        public EnumBl<PenLineCap> EndCap {
          get { return Underlying.Property<T, PenLineCap>(Shape.StrokeEndLineCapProperty); }
          set { EndCap.Bind = value; }
        }
        /// <summary>
        ///     Gets or sets a System.Windows.Media.PenLineJoin enumeration value that specifies
        ///     the type of join that is used at the vertices of a System.Windows.Shapes.Shape.
        /// </summary>
        public EnumBl<PenLineJoin> Join {
          get { return Underlying.Property<T, PenLineJoin>(Shape.StrokeLineJoinProperty); }
          set { Join.Bind = value; }
        }
        /// <summary>
        ///     Gets or sets a System.Windows.Media.PenLineCap enumeration value that describes
        ///     the System.Windows.Shapes.Shape at the start of a System.Windows.Shapes.Shape.Stroke. The default
        ///     is System.Windows.Media.PenLineCap.Flat.
        /// </summary>
        public EnumBl<PenLineCap> StartCap {
          get { return Underlying.Property<T, PenLineCap>(Shape.StrokeStartLineCapProperty); }
          set { StartCap.Bind = value; }
        }
        public LineSet Bind {
          set {
            this.EndCap.Bind = value.EndCap;
            this.StartCap.Bind = value.StartCap;
            this.Join = value.Join;
          }
        }
      }
      /// <summary>
      /// The line properties of this stroke.
      /// </summary>
      public LineSet Line {
        get { return new LineSetImpl() { Underlying = Underlying }; }
        set { Line.Bind = value; }
      }
      public StrokeSet Bind {
        set {
          this.Brush.Bind = value.Brush;
          this.Thickness.Bind = value.Thickness;
          this.MiterLimit.Bind = value.MiterLimit;
          this.Dash.Bind = value.Dash;
          this.Line.Bind = value.Line;
        }
      }
    }
    /// <summary>
    /// Properties of a shape's stroke.
    /// </summary>
    public StrokeSet Stroke {
      get { return new StrokeSetImpl() { Underlying = Provider }; }
      set { Stroke.Bind = (value); }
    }
  }
  /// <summary>
  /// Draws a shape.
  /// </summary>
  public sealed partial class ShapeBl : ShapeBl<Shape,ShapeBl> {
    public ShapeBl(Expr<Shape> Provider) : base(Provider) { }
    public ShapeBl() : base() { }
    static ShapeBl() {
    }
    public static implicit operator ShapeBl(Expr<Shape> v) { return new ShapeBl(v); }
    public static implicit operator ShapeBl(Shape s) { return new Constant<Shape>(s); }
    public static void CheckInit() { Extensions.Trace("CheckInit: " + typeof(ShapeBl) + " ToBrand=" + ToBrand); }
  }
  /// <summary>
  /// Draws a rectangle
  /// </summary>
  public partial class RectangleBl : ShapeBl<Rectangle, RectangleBl> {
    public RectangleBl(Expr<Rectangle> Provider) : base(Provider) { }
    public RectangleBl() : base(new Constant<Rectangle>(new Rectangle())) { }
    public RectangleBl(PanelBl canvas) : base(canvas, new Rectangle()) { }
    public static implicit operator RectangleBl(Expr<Rectangle> v) { return new RectangleBl(v); }


    /// <summary>
    /// set the CornerRadius to draw a Rounded Rectangle
    /// </summary>
    public Double2Bl CornerRadius {
      get { return new Double2Bl(Provider.Property<Rectangle, double>(Rectangle.RadiusXProperty), Provider.Property<Rectangle, double>(Rectangle.RadiusYProperty)); }
      set { CornerRadius.Bind = value; }
    }
  }
  /// <summary>
  /// Draws an ellipse
  /// </summary>
  public partial class EllipseBl : ShapeBl<Ellipse,EllipseBl> {
    public EllipseBl(Expr<Ellipse> Provider) : base(Provider) { }
    public EllipseBl() : base(new Constant<Ellipse>(new Ellipse())) { }
    public EllipseBl(PanelBl canvas) : base(canvas, new Ellipse()) { }
    public static implicit operator EllipseBl(Expr<Ellipse> v) { return new EllipseBl(v); }
  }
  /// <summary>
  /// Draws a line
  /// </summary>
  public partial class LineBl : ShapeBl<Line, LineBl> {
    public LineBl(Expr<Line> Provider) : base(Provider) { }
    public LineBl() : base(new Line()) { }
    public LineBl(PanelBl canvas) : base(canvas, new Line()) { }
    public Double2Bl Vector {
      get { return (End * -1d + Start); } 
    }
    public static implicit operator LineBl(Expr<Line> v) { return new LineBl(v); }

    /// <summary>
    /// Gets or sets the start point of the line
    /// </summary>
    public Double2Bl Start {
      get { return new Double2Bl(Provider.Property<Line,double>(Line.X1Property).Bl(), Provider.Property<Line,double>(Line.Y1Property)); }
      set { Start.Bind = value; }
    }
    /// <summary>
    /// Gets or sets the end point of the line
    /// </summary>
    public Double2Bl End {
      get { return new Double2Bl(Provider.Property<Line,double>(Line.X2Property).Bl(), Provider.Property<Line,double>(Line.Y2Property)); }
      set { End.Bind = value; }
    }
    public FrameworkElement EndThumb {

      set {
        FrameworkElementBl e = value.Bl();
        Opacity = e.Opacity;
        ZIndex = e.ZIndex;
        Visibility = e.Visibility;
        End.Bind = e.CenterPosition;
      }
    }

    /// <summary>
    /// initialize the line with both of its start and  end point
    /// </summary>
    [Obsolete("just set start and end directly")]
    public new LineBl Init(Double2Bl Start, Double2Bl End) {
      this.Start = Start;
      this.End = End;
      return this;
    }
    /// <summary>
    /// if draw thumbs at the both ends of the line to drag or scale
    /// </summary>
    public override bool HasThumbs {
      set {
        if (value) {
          new ThumbBl(PanelParent) {
            Background = Stroke.Brush,
            MapF = (self,p) => p.Clamp(new Point(0, 0), PanelParent.Size),
            DragPoint = Start, ZIndex = ZIndex + 1
          };
          new ThumbBl(PanelParent) {
            Background = Stroke.Brush,
            MapF = (self,p) => p.Clamp(new Point(0, 0), PanelParent.Size),
            DragPoint = End, ZIndex = ZIndex + 1
          };
        }
      }
    }
  }


  /// <summary>
  /// Defines the different orientations that a control or layout can have.
  /// </summary>
  public class OrientationBl : ValueBrand<Orientation, OrientationBl> {
    public OrientationBl(Expr<Orientation> v) : base(v) { }
    public OrientationBl() : base(Orientation.Horizontal) { }
    public static implicit operator OrientationBl(Expr<Orientation> v) { return new OrientationBl(v); }
    public static implicit operator OrientationBl(Orientation o) { return new Constant<Orientation>(o); }

    static OrientationBl() {}
    /// <summary>
    /// Gets or sets the orientation horizontal or not
    /// </summary>
    public BoolBl IsHorizontal {
      get { return this == Orientation.Horizontal; }
      set { this.Bind = value.Condition((OrientationBl) Orientation.Horizontal, Orientation.Vertical); }
    }
    /// <summary>
    /// Gets or sets the orientation vertical or not
    /// </summary>
    public BoolBl IsVertical {
      get { return !IsHorizontal; }
      set { IsHorizontal = !value; }
    }
    /// <summary>
    /// Reverse the orientation
    /// </summary>
    public OrientationBl Reverse {
      get { return IsHorizontal.Condition((OrientationBl) Orientation.Vertical, Orientation.Horizontal); }
    }
  }
  /// <summary>
  /// Specifies the display state of an element.
  /// </summary>
  public class VisibilityBl : ValueBrand<Visibility, VisibilityBl> {
    public VisibilityBl(Expr<Visibility> v) : base(v) { }
    public VisibilityBl() : base(new Visibility()) { }
    public static implicit operator VisibilityBl(Expr<Visibility> v) { return new VisibilityBl(v); }
    public static implicit operator VisibilityBl(Visibility o) { return new Constant<Visibility>(o); }
    public static implicit operator VisibilityBl(BoolBl isVisible) {
      return isVisible.Condition((VisibilityBl) Visibility.Visible, Visibility.Hidden);
    }
    public static implicit operator VisibilityBl(FlexBoolBl<D1> isVisible) {
      return isVisible.Bl();
    }
    public static implicit operator VisibilityBl(bool isVisible) {
      return isVisible.Bl();
    }
    private class AsBool : Expr<bool> {
      public Expr<Visibility> Underlying;
    protected override string ToString1() {
        return Underlying + " == Visible";
      }
      protected override int GetHashCode0() {
        return Underlying.GetHashCode();
      }
      protected override bool Equals0(Expr<bool> obj) {
        return (obj is AsBool && ((AsBool)obj).Underlying.Equals(Underlying));
      }
      protected override Eval<EVAL>.Info<bool> Eval<EVAL>(Eval<EVAL> txt) {
        return txt.DoEval((((VisibilityBl)Underlying) == ((VisibilityBl) Visibility.Visible)).Provider);
      }
      public override bool Solve(IAssign P, Expr<bool> other) {
        return Underlying.Solve(P, ((VisibilityBl) other.Bl()).Provider);
      }
    }
    public static implicit operator BoolBl(VisibilityBl isVisible) {
      return new AsBool() { Underlying = isVisible.Provider };
    }
    public static VisibilityBl operator &(VisibilityBl opA, VisibilityBl opB) {
      return ((BoolBl)opA) & ((BoolBl)opB);
    }
    public static VisibilityBl operator |(VisibilityBl opA, VisibilityBl opB) {
      return ((BoolBl)opA) | ((BoolBl)opB);
    }
    public static VisibilityBl operator !(VisibilityBl opA) {
      return !((BoolBl)opA);
    }
    static VisibilityBl() {
    }
  }


  /*

  public class ThicknessArity : Vecs.Arity4<double, Thickness, ThicknessArity> {
    public override string[] PropertyNames {
      get { return new string[] { "Left", "Top", "Right", "Bottom", }; }
    }
    public override Thickness Make(params double[] Params) {
      return new Thickness() { Left = Params[0], Top = Params[1], Right = Params[2], Bottom = Params[3] };
    }
    public override double Access(Thickness Value, int Idx) {
      switch (Idx) {
        case 0: return Value.Left;
        case 1: return Value.Top;
        case 2: return Value.Right;
        case 3: return Value.Bottom;
        default: throw new NotSupportedException();
      }
    }
  }*/

  /// <summary>
  /// Bl wrapper round the Thickness 
  ///  Describes the thickness of a frame around a rectangle. Four 
  ///     values describe the Left, Top,Right, and Bottom sides
  ///     of the rectangle, respectively.
  /// </summary>
  public class ThicknessBl {
    public ThicknessBl(Expr<Thickness> v) {
      Double4Bl v0 = v.ToBling();
      this.Left = v0.X;
      this.Top = v0.Y;
      this.Right = v0.Z;
      this.Bottom = v0.W;
    }
    public ThicknessBl(DoubleBl d) : this(d, d, d, d) { }
    /// <summary>
    ///     Initializes a new instance of the System.Windows.Thickness structure that
    ///     has specific lengths (supplied as a System.Double) applied to each side of
    ///     the rectangle.    
    ///     </summary>
    /// <param name="left">The thickness for the left side of the rectangle.</param>
    /// <param name="top">The thickness for the upper side of the rectangle.</param>
    /// <param name="right">The thickness for the right side of the rectangle.</param>
    /// <param name="bottom">The thickness for the lower side of the rectangle.</param>
    public ThicknessBl(DoubleBl left, DoubleBl top, DoubleBl right, DoubleBl bottom) {
      this.Left = left; this.Top = top; this.Right = right; this.Bottom = bottom;
    }
    /// <summary>
    /// Initializes a new instance of the System.Windows.Thickness structure that
    ///     has specific lengths (supplied as a System.Double) applied to each side of
    ///     the rectangle. 
    /// </summary>
    /// <param name="leftTop">pointBl.X:the thickness for the left side of the rectangle, and pintBl.Y:the thickness for the upper side of the rectangle.</param>
    /// <param name="rightBottom">pointBl.X:the thickness for the right side of the rectangle, and pintBl.Y:the thickness for the lower side of the rectangle.</param>
    public ThicknessBl(Double2Bl leftTop, Double2Bl rightBottom)
      : this(leftTop.X, leftTop.Y, rightBottom.X, rightBottom.Y) { }

    public static implicit operator ThicknessBl(Expr<Thickness> t) { return new ThicknessBl(t); }
    public static implicit operator ThicknessBl(Thickness t) { return new ThicknessBl(new Constant<Thickness>(t)); }
    public static implicit operator ThicknessBl(DoubleBl t) { return new ThicknessBl(t); }
    public static implicit operator ThicknessBl(double t) { return new ThicknessBl(t); }
    /// <summary>
    /// Gets the width, in pixels, of the left side of the bounding rectangle.
    /// </summary>
    public DoubleBl Left { get; set; }
    /// <summary>
    /// Gets  the hight, in pixels, of the upper side of the bounding rectangle.
    /// </summary>
    public DoubleBl Top { get; set; }

    public Double2Bl LeftTop { 
      get { return new Double2Bl(Left,Top); }
      set { Left = value.X; Top = value.Y; }
    }

    /// <summary>
    /// Gets the width, in pixels, of the right side of the bounding rectangle.
    /// </summary>
    public DoubleBl Right { get; set; }
    /// <summary>
    /// Gets the height, in pixels, of the lower side of the bounding rectangle.
    /// </summary>
    public DoubleBl Bottom { get; set; }

    public Double2Bl RightBottom { 
      get { return new Double2Bl(Right,Bottom); }
      set { Right = value.X; Bottom = value.Y; }
    }

    public Double2Bl LeftRight { 
      get { return new Double2Bl(Left,Right); }
      set { Left = value.X; Right = value.Y ; }
    }
    public Double2Bl TopBottom {
      get { return new Double2Bl(Top, Bottom); }
      set { Top = value.X; Bottom = value.Y; }
    }
    public Double4Bl All {
      get { return new Double4Bl(Left,Top,Right,Bottom); }
      set { LeftTop = value.XY(); RightBottom = value.ZW(); }
    }
    static ThicknessBl() {}
  }

  /// <summary>
  ///     Provides a custom bitmap effect.
  /// </summary>
  public abstract class EffectBl<T, BRAND> : Brand<T, BRAND>, IExtends<BRAND,EffectBl>
    where T : Effect
    where BRAND : EffectBl<T, BRAND> {
    public EffectBl(Expr<T> Provider) : base(Provider) { }
    public EffectBl() : base() { }
    public static implicit operator EffectBl(EffectBl<T, BRAND> effect) {
      return EffectBl.UpCast(effect);
    }
  }
  /// <summary>
  ///     Provides a custom bitmap effect.
  /// </summary>
  public partial class EffectBl : EffectBl<Effect, EffectBl> {
    public EffectBl(Expr<Effect> Provider) : base(Provider) { }
    public EffectBl(Effect Provider) : base(new Constant<Effect>(Provider)) { }
    public EffectBl() : base() { }
    public static implicit operator EffectBl(Expr<Effect> v) { return new EffectBl(v); }
    public static implicit operator EffectBl(Effect v) { return new EffectBl(v); }
    static EffectBl() {
    }
    public static readonly EffectBl None = new EffectBl(new Constant<Effect>(null));
  }
  public class ShaderEffectBl : EffectBl<ShaderEffect, ShaderEffectBl> {
    public ShaderEffectBl(Expr<ShaderEffect> Provider) : base(Provider) { }
    public ShaderEffectBl(ShaderEffect Provider) : this(new Constant<ShaderEffect>(Provider)) { }

    public static implicit operator ShaderEffectBl(Expr<ShaderEffect> v) { return new ShaderEffectBl(v); }
    public static implicit operator ShaderEffectBl(ShaderEffect v) { return new ShaderEffectBl(v); }
    static ShaderEffectBl() {
    }
  }

  public interface HasRenderingBias {
    EnumBl<RenderingBias> RenderingBias { get; set; }
  }

  /// <summary>
  ///     A blur effect.
  /// </summary>
  public class BlurEffectBl : EffectBl<BlurEffect, BlurEffectBl>, HasRenderingBias {
    public BlurEffectBl(Expr<BlurEffect> Provider) : base(Provider) { }
    public BlurEffectBl(BlurEffect Provider) : this(new Constant<BlurEffect>(Provider)) { }
    public BlurEffectBl() : this(new BlurEffect()) { }

    public static implicit operator BlurEffectBl(Expr<BlurEffect> v) { return new BlurEffectBl(v); }
    public static implicit operator BlurEffectBl(BlurEffect v) { return new BlurEffectBl(v); }
    static BlurEffectBl() {
    }

    /// <summary>
    /// Gets or sets a value that indicates the radius of the blur effect's curve. This is a dependency property. 
    /// </summary>
    public DoubleBl Radius {
      get { return Provider.Property<BlurEffect,double>(BlurEffect.RadiusProperty); }
      set { Radius.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value that indicates whether the system renders an effect
    ///     with emphasis on speed or quality. This is a dependency property. The default
    ///     is System.Windows.Media.Effects.RenderingBias.Performance.
    /// </summary>
    public EnumBl<RenderingBias> RenderingBias {
      get { return Provider.Property<BlurEffect,RenderingBias>(BlurEffect.RenderingBiasProperty); }
      set { RenderingBias.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value representing the curve that is used to calculate the
    ///     blur. This is a dependency property. The default is System.Windows.Media.Effects.KernelType.Gaussian.
    /// </summary>
    public EnumBl<KernelType> KernelType {
      get { return Provider.Property<BlurEffect,KernelType>(BlurEffect.KernelTypeProperty); }
      set { KernelType.Bind = value; }
    }
  }
  /// <summary>
  ///     A bitmap effect that paints a drop shadow around the target texture.
  /// </summary>
  public class DropShadowEffectBl : EffectBl<DropShadowEffect, DropShadowEffectBl>, HasRenderingBias {
    public DropShadowEffectBl(Expr<DropShadowEffect> Provider) : base(Provider) { }
    public DropShadowEffectBl(DropShadowEffect Provider) : this(new Constant<DropShadowEffect>(Provider)) { }
    public DropShadowEffectBl() : this(new DropShadowEffect()) { }

    public static implicit operator DropShadowEffectBl(Expr<DropShadowEffect> v) { return new DropShadowEffectBl(v); }
    public static implicit operator DropShadowEffectBl(DropShadowEffect v) { return new DropShadowEffectBl(v); }
    static DropShadowEffectBl() {
    }

    /// <summary>
    ///     A value that indicates the radius of the shadow's blur effect. The default
    ///     is 5.
    /// </summary>
    public DoubleBl BlurRadius {
      get { return Provider.Property<DropShadowEffect,double>(DropShadowEffect.BlurRadiusProperty); }
      set { BlurRadius.Bind = value; }
    }
    /// <summary>
    ///     The color of the drop shadow. The default is System.Windows.Media.Colors.Black.
    /// </summary>
    public ColorBl Color {
      get { return Provider.Property<DropShadowEffect,Color>(DropShadowEffect.ColorProperty); }
      set { Color.Bind = value; }
    }
    /// <summary>
    ///     The direction of the drop shadow, in degrees. The default is 315.
    /// </summary>
    public DegreeBl Direction {
      get { return Provider.Property<DropShadowEffect,double>(DropShadowEffect.DirectionProperty).Bl().Degrees(); }
      set { Direction.Bind = value; }
    }
    /// <summary>
    ///     The opacity of the drop shadow. The default is 1.
    /// </summary>
    public DoubleBl Opacity {
      get { return Provider.Property<DropShadowEffect,double>(DropShadowEffect.OpacityProperty); }
      set { Opacity.Bind = value; }
    }
    /// <summary>
    ///     The distance of the drop shadow below the texture. The default is 5.
    /// </summary>
    public DoubleBl ShadowDepth {
      get { return Provider.Property<DropShadowEffect,double>(DropShadowEffect.ShadowDepthProperty); }
      set { ShadowDepth.Bind = value; }
    }
    /// <summary>
    ///     A System.Windows.Media.Effects.RenderingBias value that indicates whether
    ///     the system renders the drop shadow with emphasis on speed or quality. The
    ///     default is System.Windows.Media.Effects.RenderingBias.Performance.
    /// </summary>
    public EnumBl<RenderingBias> RenderingBias {
      get { return Provider.Property<DropShadowEffect,RenderingBias>(DropShadowEffect.RenderingBiasProperty); }
      set { RenderingBias.Bind = value; }
    }
  }

  /// <summary>
  ///  Represents the class for user interface (UI) elements that use a System.Windows.Controls.ControlTemplate
  //     to define their appearance.
  /// </summary>
  public sealed partial class ControlBl : ControlBl<Control, ControlBl> {
    public ControlBl(Expr<Control> Provider) : base(Provider) { }
  }
  public abstract class ButtonBaseBl<T, SELF> : ContentControlBl<T, SELF>
    where T : ButtonBase
    where SELF : ButtonBaseBl<T, SELF> {
    public ButtonBaseBl(Expr<T> Provider) : base(Provider) { }
    public ButtonBaseBl() : base() { }
    public ButtonBaseBl(PanelBl canvas, T target) : base(canvas, target) { }
    /// <summary>
    ///     Gets a value that indicates whether a System.Windows.Controls.Primitives.ButtonBase
    ///     is currently activated. This is a dependency property.
    ///
    /// Returns true if the System.Windows.Controls.Primitives.ButtonBase is activated; otherwise
    ///     false. The default is false.    
    /// </summary>
    public BoolBl IsPressed {
      get { return Provider.Property<T,bool>(ButtonBase.IsPressedProperty); }
    }
    /// <summary>
    /// Occurs when a System.Windows.Controls.Button is clicked.    
    /// </summary>
    public EventStream Click1 {
      get {
        return new DefaultEventStream<RoutedEventHandler>() {
          Transform = a => (x, y) => a(),
          Add = a => CurrentValue.Click += a,
          Remove = a => CurrentValue.Click -= a,
        };
      }
    }

    public Action Click {
      set { CurrentValue.Click += (x, y) => value(); }
    }
    public Action<SELF> Click0 {
      set { CurrentValue.Click += (x, y) => value(this); }
    }
  }
  /// <summary>
  ///     Represents a Windows button control, which reacts to the System.Windows.Controls.Primitives.ButtonBase.Click
  ///     event.
  /// </summary>
  public class ButtonBl : ButtonBaseBl<Button, ButtonBl> {
    public ButtonBl(Expr<Button> Provider) : base(Provider) { }
    public ButtonBl() : base(new Constant<Button>(new Button())) { }
    public ButtonBl(PanelBl canvas) : base(canvas, new Button()) { }
    /// <summary>
    ///     Gets or sets a value that indicates whether a System.Windows.Controls.Button
    ///     is a Cancel button. A user can activate the Cancel button by pressing the
    ///     ESC key. This is a dependency property. Returns true if the System.Windows.Controls.Button is a Cancel button; otherwise,
    ///     false. The default is false.
    /// </summary>
    public BoolBl IsCancel {
      get { return Provider.Property<Button, bool>(Button.IsCancelProperty); }
      set { IsCancel.Bind = value; }
    }
    /// <summary>
    ///     Gets a value that indicates whether a System.Windows.Controls.Button is the
    ///     button that is activated when a user presses ENTER. This is a dependency
    ///     property. Returns true if the button is activated when the user presses ENTER; otherwise, false.
    ///     The default is false.
    /// </summary>
    public BoolBl IsDefaulted {
      get { return Provider.Property<Button, bool>(Button.IsDefaultedProperty); }
      set { IsDefaulted.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value that indicates whether a System.Windows.Controls.Button
    ///     is the default button. A user invokes the default button by pressing the
    ///     ENTER key. This is a dependency property. Returns true if the System.Windows.Controls.Button 
    ///     is the default button; otherwise, false. The default is false.
    /// </summary>
    public BoolBl IsDefault {
      get { return Provider.Property<Button, bool>(Button.IsDefaultProperty); }
      set { IsDefault.Bind = value; }
    }
  }
  /// <summary>
  ///     Base class for controls that can switch states, such as System.Windows.Controls.CheckBox.
  /// </summary>
  public class ToggleButtonBl : ToggleButtonBl<ToggleButton, ToggleButtonBl> {
    public ToggleButtonBl(Expr<ToggleButton> Provider) : base(Provider) { }
    public ToggleButtonBl() : base(new ToggleButton()) { }
    public ToggleButtonBl(PanelBl canvas) : base(canvas, new ToggleButton()) { }
  }
  public class ContentControlBl : ContentControlBl<ContentControl, ContentControlBl> {
    public ContentControlBl(Expr<ContentControl> Provider) : base(Provider) { }
    public ContentControlBl() : base() { }
    public ContentControlBl(PanelBl canvas) : base(canvas, new ContentControl()) { }
    public static implicit operator ContentControlBl(Expr<ContentControl> c) { return new ContentControlBl(c); }
    public static implicit operator ContentControlBl(ContentControl c) { return new Constant<ContentControl>(c); }
  }

  public abstract partial class ContentControlBl<T,BRAND> : ControlBl<T,BRAND>, IExtends<BRAND,ContentControlBl> where T : ContentControl where BRAND : ContentControlBl<T,BRAND> {
    public ContentControlBl(Expr<T> Provider) : base(Provider) { }
    public ContentControlBl() : base() { }
    public ContentControlBl(PanelBl canvas, T target) : base(canvas, target) { }
    public static implicit operator ContentControlBl(ContentControlBl<T, BRAND> c) {
      return ContentControlBl.UpCast(c);
    }

    /// <summary>
    ///    Gets or sets the content of a System.Windows.Controls.ContentControl. This
    ///     is a dependency property.
    /// </summary>
    /// <returns>
    ///    An object that contains the control's content. The default value is null.
    ///</returns>    
    public ObjectBl Content {
      get { return Provider.Property<T,object>(ContentControl.ContentProperty); }
      set { Content.Bind = value; }
    }


  }

  /// <summary>
  /// Represents the text label for a control and provides support for access keys.
  /// </summary>
  public partial class LabelBl : ContentControlBl<Label, LabelBl> {
    public LabelBl(Expr<Label> Provider) : base(Provider) { }
    public LabelBl() : this(new Constant<Label>(new Label())) { }
    public LabelBl(PanelBl canvas)
      : base(canvas, new Label()) {
    }
    static LabelBl() {
    }
    public static implicit operator LabelBl(Expr<Label> v) { return new LabelBl(v); }

  }


  /// <summary>
  /// Represents a control that can be dragged by the user.
  /// </summary>
  public partial class ThumbBl : ControlBl<Thumb, ThumbBl> {
    public ThumbBl(Expr<Thumb> Provider) : base(Provider) { }
    public ThumbBl() : this(new Constant<Thumb>(new Thumb())) { }
    public ThumbBl(PanelBl canvas)
      : base(canvas, new Thumb()) {
      Size = new Point(10, 10);
    }
    //public static implicit operator PointWp(ThumbBl thumb) { return thumb.CenterPosition; }
    public static implicit operator Double2Bl(ThumbBl thumb) { return thumb.CenterPosition; }

    public Func<ThumbBl,Double2Bl, Double2Bl> MapF = (self,p) => p;


    private Action<Point> CanDragF;

    public Action<ThumbBl,Double2Bl> CanDragG {
      set {
        CanDragF = (p) => value(this,p);

      }
    }

    /// <summary>
    /// set the thumb if can be dragged
    /// </summary>
    public bool CanDrag {
      set {
        if (value) {
          if (CanDragF == null) {
            CanDragF = Double2Bl.Assign<Point>(p => LeftTop, (p,lhs) => MapF(this, lhs + p.Bl()));

          }
          ((Thumb)this.CurrentValue).DragDelta += (x, y) => CanDragF((Point)y.Delta());
            
            //((Thumb)x).Bl().LeftTop.Now = Map(this, ((Thumb)x).Bl().LeftTop + y.Delta());
        } 
      }
    }
    /// <summary>
    /// set the dragpoint
    /// </summary>
    public Double2Bl DragPoint {
      set {
        this.CenterPosition.Bind = value;
        ((Thumb)this.CurrentValue).DragDelta += (x, y) => value.Now = MapF(this, value + ((Double2Bl)(Point) y.Delta()));
      }
    }
    /// <summary>
    /// Is this thumb currently being dragged by the user?
    /// </summary>
    public BoolBl IsDragging {
      get { return Provider.Property<Thumb,bool>(Thumb.IsDraggingProperty); }
    }

    static ThumbBl() {
    }
    public static implicit operator ThumbBl(Expr<Thumb> v) { return new ThumbBl(v); }

  }


  public class GeometryBl<T,BRAND> : Brand<T,BRAND>, IExtends<BRAND,GeometryBl> where T : Geometry where BRAND : GeometryBl<T,BRAND> {
    public GeometryBl(Expr<T> Provider) : base(Provider) { }
    public GeometryBl() : base() { }
    public static implicit operator GeometryBl(GeometryBl<T, BRAND> v) {
      return GeometryBl.UpCast(v) ;
    }
    /// <summary>
    ///     Gets or sets the System.Windows.Media.Transform object applied to a System.Windows.Media.Geometry.
    ///     This is a dependency property.
    ///     The transformation applied to the System.Windows.Media.Geometry. Note that
    ///     this value may be a single System.Windows.Media.Transform or a System.Windows.Media.TransformCollection
    ///     cast as a System.Windows.Media.Transform.
    /// </summary>
    public TransformBl Transform {
      get {
        return new TransformBl(Provider.Property<T,Transform>(Geometry.TransformProperty));
      }
      set {
        Transform.Bind = value;
      }
    }
    public static PathGeometryBl operator +(GeometryBl op0, GeometryBl<T,BRAND> op1) {
      return (Geometry.Combine(op0.CurrentValue, op1.CurrentValue, GeometryCombineMode.Union, null));
    }
    public static PathGeometryBl operator -(GeometryBl op0, GeometryBl<T, BRAND> op1) {
      return (Geometry.Combine(op0.CurrentValue, op1.CurrentValue, GeometryCombineMode.Exclude, null));
    }
    public static PathGeometryBl operator *(GeometryBl op0, GeometryBl<T, BRAND> op1) {
      return (Geometry.Combine(op0.CurrentValue, op1.CurrentValue, GeometryCombineMode.Intersect, null));
    }
    public static PathGeometryBl operator ^(GeometryBl op0, GeometryBl<T, BRAND> op1) {
      return (Geometry.Combine(op0.CurrentValue, op1.CurrentValue, GeometryCombineMode.Xor, null));
    }
  }
  /// <summary>
  ///     Represents a complex shape that may be composed of arcs, curves, ellipses,
  ///     lines, and rectangles.
  /// </summary>
  public partial class PathGeometryBl : GeometryBl<PathGeometry, PathGeometryBl> {
    public PathGeometryBl(Expr<PathGeometry> Provider) : base(Provider) { }
    public PathGeometryBl() : this(new Constant<PathGeometry>(new PathGeometry())) { }
    public static implicit operator PathGeometryBl(Expr<PathGeometry> v) { return new PathGeometryBl(v); }
    public static implicit operator PathGeometryBl(PathGeometry geom) { return new PathGeometryBl(new Constant<PathGeometry>(geom)); }

    /// <summary>
    ///     Gets or sets the collection of System.Windows.Media.PathFigure objects that
    ///     describe the path's contents. This is a dependency property.
    ///     A collection of System.Windows.Media.PathFigure objects that describe the
    ///     path's contents. Each individual System.Windows.Media.PathFigure describes
    ///     a shape.
    /// </summary>
    public CollectionBl<PathFigure,PathFigureBl,PathFigureCollection> Figures {
      get { return Provider.Property<PathGeometry, PathFigureCollection>(PathGeometry.FiguresProperty); }
      set { Figures.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value that determines how the intersecting areas contained
    ///     in this System.Windows.Media.PathGeometry are combined. This is a dependency
    ///     property. Indicates how the intersecting areas of this System.Windows.Media.PathGeometry
    ///     are combined. The default value is EvenOdd.
    /// </summary>
    public EnumBl<FillRule> FillRule {
      get { return Provider.Property<PathGeometry, FillRule>(PathGeometry.FillRuleProperty); }
      set { FillRule.Bind = value; }
    }
  }
  /// <summary>
  /// Represents a subsection of a geometry, a single connected series of two-dimensional
  ///     geometric segments.
  /// </summary>
  public partial class PathFigureBl : Brand<PathFigure, PathFigureBl> {
    public static implicit  operator PathFigureBl(Expr<PathFigure> e) { return new PathFigureBl(e); }

    public PathFigureBl(Expr<PathFigure> Provider) : base(Provider) { }
    public PathFigureBl() : this(new PathFigure()) { }
    /// <summary>
    ///    Gets or sets the Point where the PathFigure
    ///     begins. This is a dependency property. The default value is 0,0.
    /// </summary>    
    public Double2Bl StartPoint {
      get { return Provider.Property<PathFigure,Point>(PathFigure.StartPointProperty).Bl(); }
      set { StartPoint.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets a value that specifies whether this figures first and last segments
    ///     are connected. This is a dependency property.
    ///     The default value is false.
    /// </summary>    
    public BoolBl IsClosed {
      get { return Provider.Property<PathFigure, bool>(PathFigure.IsClosedProperty).Bl(); }
      set { IsClosed.Bind = value; }
    }
    /// <summary>
    ///     Gets or sets whether the contained area of this System.Windows.Media.PathFigure
    ///     is to be used for hit-testing, rendering, and clipping. This is a dependency
    ///     property. The default value
    ///     is true.
    ///</summary>    
    public BoolBl IsFilled {
      get { return Provider.Property<PathFigure, bool>(PathFigure.IsFilledProperty); }
      set { IsFilled.Bind = value; }
    }

    /// <summary>
    ///     Gets or sets the collection of segments that define the shape of this System.Windows.Media.PathFigure
    ///     object. This is a dependency property. The default value is an empty collection.
    /// </summary>    
    public CollectionBl<PathSegment,PathSegmentBl,PathSegmentCollection> Segments {
      get { return Provider.Property<PathFigure,PathSegmentCollection>(PathFigure.SegmentsProperty); }
      set { Segments.Bind = value; }
    }
  }
  /// <summary>
  /// Represents a segment of a System.Windows.Media.PathFigure object.
  /// </summary>
  /// <typeparam name="TARGET"></typeparam>
  public abstract partial class PathSegmentBl<T,BRAND> : Brand<T,BRAND>, IExtends<BRAND,PathSegmentBl> where T : PathSegment where BRAND : PathSegmentBl<T,BRAND> {
    public PathSegmentBl(Expr<T> Provider) : base(Provider) { }
    public PathSegmentBl() : base() { }
    public static implicit operator T(PathSegmentBl<T, BRAND> s) { return s.CurrentValue; }

    /// <summary>
    ///     Gets or sets a value that indicates whether the join between this System.Windows.Media.PathSegment
    ///     and the previous System.Windows.Media.PathSegment is treated as a corner
    ///     when it is stroked with a System.Windows.Media.Pen. This is a dependency
    ///     property.
    /// </summary>
    /// <returns>
    ///     true if the join between this System.Windows.Media.PathSegment and the previous
    ///     System.Windows.Media.PathSegment is not to be treated as a corner; otherwise,
    ///     false. The default is false.
    /// </returns>
    public BoolBl IsSmoothJoin {
      get { return Provider.Property<T,bool>(PathSegment.IsSmoothJoinProperty).Bl(); }
      set { IsSmoothJoin.Bind = value; }
    }
    /// <summary>
    ///   Gets or sets a value that indicates whether the segment is stroked. This
    ///     is a dependency property.
    /// </summary>
    /// <returns>
    ///   true if the segment is stroked when a System.Windows.Media.Pen is used to
    ///     render the segment; otherwise, the segment is not stroked. The default is
    ///     true.
    /// </returns>
    public BoolBl IsStroked {
      get { return Provider.Property<T,bool>(PathSegment.IsStrokedProperty).Bl(); }
      set { IsStroked.Bind = value; }
    }
    public static implicit operator PathSegmentBl(PathSegmentBl<T, BRAND> value) {
      return PathSegmentBl.UpCast(value);
    }
    static PathSegmentBl() {
      PathSegmentBl.CheckInit();
    }
  }
  /// <summary>
  ///     Represents a segment of a System.Windows.Media.PathFigure object.
  /// </summary>
  public class PathSegmentBl : PathSegmentBl<PathSegment, PathSegmentBl> {
    public PathSegmentBl(Expr<PathSegment> Underlying) : base(Underlying) { }
    public PathSegmentBl() : base() { }
    public static implicit operator PathSegmentBl(Expr<PathSegment> target) { return new PathSegmentBl((target)); }
    public static implicit operator PathSegmentBl(PathSegment target) { return (new Constant<PathSegment>(target)); }
    public static implicit operator PathSegmentBl(Double2Bl p) {
      return new LineSegmentBl() { Point = p };
    }
    public static void CheckInit() { Extensions.Trace("CheckInit: " + typeof(PathSegmentBl) + " ToBrand=" + ToBrand); }

  }
  /// <summary>
  /// Represents a cubic Bezier curve drawn between two points.
  /// </summary>
  public partial class BezierSegmentBl : PathSegmentBl<BezierSegment, BezierSegmentBl> {
    public BezierSegmentBl(Expr<BezierSegment> Provider) : base(Provider) { }
    public BezierSegmentBl() : this(new BezierSegment()) { }
    public static implicit operator BezierSegmentBl(Expr<BezierSegment> v) { return new BezierSegmentBl(v); }
    /// <summary>
    ///  All points of this curve.
    /// </summary>
    /// <param name="Start">Start point of curve that is implicit in preceding segment or figure start point.</param>
    public Double2Bl[] Points(Double2Bl Start) {
      return new Double2Bl[] { Start, Point1, Point2, Point3 };
    }
    /// <summary>
    /// The first control point.
    /// </summary>
    public Double2Bl Point1 {
      get { return Provider.Property<BezierSegment,Point>(BezierSegment.Point1Property).Bl(); }
      set { Point1.Bind = value; }
    }
    /// <summary>
    /// The second control point.
    /// </summary>
    public Double2Bl Point2 {
      get { return Provider.Property<BezierSegment,Point>(BezierSegment.Point2Property).Bl(); }
      set { Point2.Bind = value; }
    }
    /// <summary>
    /// The end control point.
    /// </summary>
    public Double2Bl Point3 {
      get { return Provider.Property<BezierSegment, Point>(BezierSegment.Point3Property).Bl(); }
      set { Point3.Bind = value; }
    }
  }
  /// <summary>
  ///     Creates a line between two points in a System.Windows.Media.PathFigure.
  /// </summary>
  public partial class LineSegmentBl : PathSegmentBl<LineSegment, LineSegmentBl> {
    public LineSegmentBl(Expr<LineSegment> Provider) : base(Provider) { }
    public LineSegmentBl() : this(new LineSegment()) { }
    public static implicit operator LineSegmentBl(Expr<LineSegment> v) { return new LineSegmentBl(v); }
    public static implicit operator LineSegmentBl(LineSegment v) { return new Constant<LineSegment>(v); }
    /// <summary>
    /// Gets or sets the end point of the line segment. This is a dependency property.
    /// </summary>
    public Double2Bl Point {
      get { return Provider.Property<LineSegment,Point>(LineSegment.PointProperty).Bl(); }
      set { Point.Bind = value; }
    }
  }
  /// <summary>
  /// reates a quadratic Bezier curve between two points in a PathFigure.
  /// </summary>
  public partial class QuadraticBezierSegmentBl : PathSegmentBl<QuadraticBezierSegment, QuadraticBezierSegmentBl> {
    public QuadraticBezierSegmentBl(Expr<QuadraticBezierSegment> Provider) : base(Provider) { }
    public QuadraticBezierSegmentBl() : this(new QuadraticBezierSegment()) { }
    public static implicit operator QuadraticBezierSegmentBl(Expr<QuadraticBezierSegment> v) { return new QuadraticBezierSegmentBl(v); }
    public static implicit operator QuadraticBezierSegmentBl(QuadraticBezierSegment v) { return new Constant<QuadraticBezierSegment>(v); }
    static QuadraticBezierSegmentBl() {
    }
    /* TODO
    public PointBl this[PointBl Start, DoubleBl t, int idx] {
      get { return PointBl.Bezier(t, idx, Points(Start)); }
      set { this[Start, t, idx].Bind = value; }
    }
     */

    /// <summary>
    /// All control points of this curve.
    /// </summary>
    /// <param name="Start">Start point that is implicit in preceding figure or figure start point.</param>
    public Double2Bl[] Points(Double2Bl Start) {
      return new Double2Bl[] { Start, Point1, Point2 };
    }
    /// <summary>
    /// The control point
    /// </summary>
    public Double2Bl Point1 {
      get { return Provider.Property<QuadraticBezierSegment,Point>(QuadraticBezierSegment.Point1Property).Bl(); }
      set { Point1.Bind = value; }
    }
    public class MidPointX {
      internal QuadraticBezierSegmentBl Target { private get; set; }
      public Double2Bl this[Double2Bl start, DoubleBl t] {
        get {
          return GeometryExtensions.MidPoint(start, Target.Point1, Target.Point2, t);
        }
        set {
          this[start, t].Bind = value;
        }
      }
    }
    public MidPointX MidPoint { get { return new MidPointX() { Target = this }; } }


    /// <summary>
    /// The end point
    /// </summary>
    public Double2Bl Point2 {
      get { return Provider.Property<QuadraticBezierSegment,Point>(QuadraticBezierSegment.Point2Property).Bl(); }
      set { Point2.Bind = value; }
    }
  }
  /// <summary>
  ///     Represents an elliptical arc between two points.
  /// </summary>
  public partial class ArcSegmentBl : PathSegmentBl<ArcSegment, ArcSegmentBl> {
    public ArcSegmentBl(Expr<ArcSegment> Provider) : base(Provider) { }
    public ArcSegmentBl() : this(new ArcSegment()) { }
    public static implicit operator ArcSegmentBl(Expr<ArcSegment> v) { return new ArcSegmentBl(v); }
    /// <summary>
    ///     Gets or sets the endpoint of the elliptical arc. This is a dependency property. The default value is (0,0).
    /// </summary>
    public Double2Bl Point {
      get { return Provider.Property<ArcSegment,Point>(ArcSegment.PointProperty).Bl(); }
      set { Point.Bind = value; }
    }
    /// <summary>
    ///     A System.Windows.Size structure that describes the x- and y-radius of the
    ///     elliptical arc. The System.Windows.Size structure's System.Windows.Size.Width
    ///     property specifies the arc's x-radius; its System.Windows.Size.Height property
    ///     specifies the arc's y-radius. The default value is 0,0.
    /// </summary>
    public Double2Bl Size {
      get {
        return Provider.Property<ArcSegment,Size>(ArcSegment.SizeProperty);
      }
      set { Size.Bind = value; }
    }
    /// <summary>
    /// Like size except the x and y radius are made the same. 
    /// </summary>
    public DoubleBl Radius {
      get {
        var sz = Size;
        sz.Y = sz.X;
        return sz.X;
      }
      set { Radius.Bind = value; }
    }
    /// <summary>
    ///     The amount (in degrees) by which the ellipse is rotated about the x-axis.
    ///     The default value is 0.
    /// </summary>
    public DegreeBl RotationAngle {
      get { return Provider.Property<ArcSegment,double>(ArcSegment.RotationAngleProperty).Bl().Degrees(); }
      set { RotationAngle.Bind = value; }
    }
    /// <summary>
    ///     A value that specifies the direction in which the arc is drawn. The default
    ///     value is System.Windows.Media.SweepDirection.Counterclockwise.
    /// </summary>
    public EnumBl<SweepDirection> SweepDirection {
      get { return Provider.Property<ArcSegment,SweepDirection>(ArcSegment.SweepDirectionProperty); }
      set { SweepDirection.Bind = value; }
    }
    /// <summary>
    ///     True if the arc should be greater than 180 degrees; otherwise, false. The
    ///     default value is false.
    /// </summary>
    public BoolBl IsLargeArc {
      get {
        return Provider.Property<ArcSegment, bool>(ArcSegment.IsLargeArcProperty);
      }
      set {
        IsLargeArc.Bind = value;
      }
    }
  }
  public static partial class WPFExtensions {
    private static void InitB() {
      Double4Bl.SetWPFProperties<Thickness>(
        typeof(Thickness).GetProperty("Left"),
        typeof(Thickness).GetProperty("Top"),
        typeof(Thickness).GetProperty("Right"),
        typeof(Thickness).GetProperty("Bottom")
      );
      Double4Bl.SetWPFProperties<CornerRadius>(
        typeof(CornerRadius).GetProperty("BottomLeft"),
        typeof(CornerRadius).GetProperty("BottomRight"),
        typeof(CornerRadius).GetProperty("TopLeft"),
        typeof(CornerRadius).GetProperty("TopRight")
      );
    }
    public static EventStream RepeatAlarmUI(this TimeSpan span) {
      if (span == TimeSpan.Zero) return EventStream.Null;
      return new AlarmEventStream(() => span, EventStream.Null) { DoRepeat = true };
    }
    public static EventStream AlarmUI(this TimeSpan span) {
      if (span == TimeSpan.Zero) return EventStream.Null;
      return new AlarmEventStream(() => span, EventStream.Null);
    }
    public static EventStream AlarmUI(this TimeSpanBl span) {
      return new AlarmEventStream(span.AsFunc, span.Changed);
    }

    private class AlarmEventStream : ExplicitEventStream {
      public readonly DispatcherTimer timer = new DispatcherTimer();
      private readonly Func<TimeSpan> span;
      //private readonly EventStream SpanChanged;
      internal bool DoRepeat = false;
      public AlarmEventStream(Func<TimeSpan> span, EventStream SpanChanged) {
        Listeners = new List<Action>();
        timer.Tick += (x, y) => {
          timer.Stop();
          Listeners.Flush();
        };
        this.span = span;
        //this.SpanChanged = SpanChanged;
      }
      public override Action Subscribe(Action a) {
        var interval = span();
        if (interval == TimeSpan.Zero) return () => { };
        timer.Interval = interval;
        if (!timer.IsEnabled) {
          timer.Start();
        }
        return base.Subscribe(a);
      }
    }

    public static Expr<Vecs.IVec<double, D4>> ToBling(this Expr<Thickness> u) {
      return WPFConversions<double, D4, Thickness>.ToBling.Instance.Make(u);
    }
    public static PanelBl Bl(this Expr<Panel> u) { return new PanelBl(u); }

    public static ThicknessBl Bl(this Expr<Thickness> u) {
      return u;
    }
    public static Expr<Vecs.IVec<double, D4>> ToBling(this Expr<CornerRadius> u) {
      return WPFConversions<double, D4, CornerRadius>.ToBling.Instance.Make(u);
    }



    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static QuadraticBezierSegmentBl Bl(this QuadraticBezierSegment element) {
      return new QuadraticBezierSegmentBl(new Constant<QuadraticBezierSegment>(element));
    }
    public static ImageSourceBl Bl(this ImageSource element) {
      return element;
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static BezierSegmentBl Bl(this BezierSegment element) {
      return new BezierSegmentBl(new Constant<BezierSegment>(element));
    }
    public static BezierSegment BezierSegment(this Double2Bl[] points) {
      return new BezierSegmentBl() {
        Point1 = points[0],
        Point2 = points[1],
        Point3 = points[2],
      };
    }
    public static BezierSegment PolygonSegment(this DoubleBl smoothValue, params Double2Bl[] Points) {
      return BezierSegment(GeometryExtensions.PolygonSegment(smoothValue, Points));
    }



    public static LineSegmentBl Bl(this LineSegment element) {
      return new LineSegmentBl(new Constant<LineSegment>(element));
    }

    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static PathFigureBl Bl(this PathFigure element) {
      return new PathFigureBl(new Constant<PathFigure>(element));
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static FrameworkElementBl Bl(this FrameworkElement element) {
      return (element);
    }
    /*
    public static FrameworkElementBl Bl0<T>(this Expr<T> element) where T : FrameworkElement {
      return FrameworkElementBl.UpCast<T>(element);
    }
    */


    public static ImageBl Bl(this Image element) {
      return (element);
    }

    /*
    public static FrameworkElementBl Bl(this FrameworkElement[] elements, IntBl index) {
      return new FrameworkElementBl(elements.BlA(index));
    }
     */
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static SliderBl Bl(this Slider element) {
      return new SliderBl(element);
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static ShapeBl Bl(this Shape element) {
      return new ShapeBl(element);
    }
    /*
    public static ShapeBl Bl(this Shape[] elements, IntBl index) {
      return new ShapeBl(elements.BlA(index));
    }
     */
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static LineBl Bl(this Line element) {
      return new LineBl(element);
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static RectangleBl Bl(this Rectangle element) {
      return new RectangleBl(element);
    }

    /*
    public static RectBl Bl(this Value<Rect> element) {
      return (element);
    }
     */
    public static OrientationBl Bl(this Expr<Orientation> element) {
      return (element);
    }
    public static OrientationBl Bl(this Orientation element) {
      return (element);
    }/*
    public static RectBl Bl(this Rect element) {
      return (element);
    }*/

    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static EllipseBl Bl(this Ellipse element) {
      return new EllipseBl(element);
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static ControlBl Bl(this Control element) {
      return new ControlBl(element);
    }

    public static WindowBl Bl(this Window element) {
      return new WindowBl(element);
    }

    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static PanelBl Bl(this Panel element) {
      return new PanelBl(element);
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static CanvasBl Bl(this Canvas element) {
      return CanvasBl.Make(new Constant<Canvas>(element));
    }
    public static CanvasBl Bl(this Expr<Canvas> element) {
      return CanvasBl.Make((element));
    }

    public static ContentControlBl Bl(this ContentControl element) {
      return element;
    }

    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static ThumbBl Bl(this Thumb element) {
      return new ThumbBl(element);
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static SolidColorBrushBl Bl(this SolidColorBrush element) {
      return new SolidColorBrushBl(element);
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static ImageBrushBl Bl(this ImageBrush element) {
      return new ImageBrushBl(element);
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static ImageSourceBl Bl(this Expr<ImageSource> element) {
      return new ImageSourceBl(element);
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static DrawingBl Bl(this Expr<Drawing> element) {
      return new DrawingBl(element);
    }
    /// <summary>
    /// Create WPF Bl wrapper around this object.
    /// </summary>
    public static GeometryBl Bl(this Expr<Geometry> element) {
      return new GeometryBl(element);
    }
    public static GeometryBl Bl(this Geometry element) {
      return element;
    }
    public static PathGeometryBl Bl(this PathGeometry element) {
      return element;
    }

    /// <summary>
    /// Create a line segement bound to this point.
    /// </summary>
    public static LineSegmentBl Segment(this Double2Bl point) {
      var ret = new LineSegmentBl();
      ret.Point.Bind = point;
      return ret;
    }
    /// <summary>
    /// Install multiple line segments on this path figure.
    /// </summary>
    /// <param name="points">Points of the line segments to install.</param>
    public static void Segments(this PathFigure figure, params Double2Bl[] points) {
      foreach (var p in points) {
        var ret = p.Segment();
        figure.Segments.Add(ret);
      }
    }
    /// <summary>
    /// Create a line segement bound to this point and added to figure.
    /// </summary>
    public static LineSegment Segment(this Double2Bl point, PathFigureBl figure) {      
      var ret = point.Segment();
      figure.Segments.Add(ret);
      return ret;
    }
  }
}


